Python中的欧几里德算法/ GCD

时间:2014-02-06 16:32:37

标签: python

我正在尝试用Python编写欧几里德算法。这是找到两个非常大的数字的GCD。公式是a = bq + r,其中a和b是你的两个数字,q是b均匀分割的次数,r是余数。

我可以编写代码来找到它,但是如果它原始数字不产生零的余数(r)那么算法转到步骤2 => b = rx + y。 (与第一步相同,但简单地将b替换为a,r替换为b)两个步骤重复,直到r均匀地划分a和b两者。

这是我的代码,我还没有弄清楚如何进行值的修改并创建一个循环,直到找到GCD。

a = int(input("What's the first number? "))
b = int(input("What's the second number? ")) 
r = int(a - (b)*int(a/b))

if r == 0:
  print("The GCD of the two choosen numbers is " + str(b))

elif r != 0:
  return b and r
  (b == a) and (r == b)

print("The GCD of the two numbers is " + str(r))

4 个答案:

答案 0 :(得分:2)

a = int(input("What's the first number? "))
b = int(input("What's the second number? ")) 
r=a%b
while r:
    a=b
    b=r
    r=a%b
print('GCD is:', b)

或在循环中使用break

a = int(input("What's the first number? "))
b = int(input("What's the second number? ")) 
while 1:
    r=a%b
    if not r:
        break
    a=b
    b=r
print('GCD is:', b)

答案 1 :(得分:0)

您可以定义一个函数并从定义中调用该函数。试试这个:

#!/usr/bin/env python

def euclid_algo(n, m):  #  where n > m
    r = n % m
    if r == 0:
        print "gcd(%d, %d) = %d" %(a, b, m)
    else:
        euclid_algo(m, r)

a = 35047
b = 101

euclid_algo(a, b)

# out[1]:  gcd(35047, 101) = 101

答案 2 :(得分:0)

尝试

a = int(input("Enter No.1"))

b = int(input("Enter No.2"))

r = a%b

q = int(a/b)

while(r!=0):

    a = b

    b = r

    q = int(a/b)

    r = a - (b * q)


print(b)

答案 3 :(得分:0)

我知道这是旧帖子,但在这里:

def GCD(x , y):
    """This is used to calculate the GCD of the given two numbers.
    You remember the farm land problem where we need to find the 
    largest , equal size , square plots of a given plot?"""
    if y == 0:
        return x
    r = int(x % y)
    return GCD(y , r)

摘自《算法》第 4 版。

注意:如果您的数字非常大,请尝试通过以下方式增加递归限制:

import sys
sys.seterecursionlimit("your new limit")

但要非常小心。我能够填满我的 12GB RAM 并很容易导致冻结。

相关问题