121

a 和 b 的最大公约数 (GCD) 是除以它们而没有余数的最大数。

找到两个数的 GCD 的一种方法是欧几里德算法,该算法基于以下观察结果:如果是除以r时的余数,则。作为基本情况,我们可以使用.abgcd(a, b) = gcd(b, r)gcd(a, 0) = a

编写一个名为 gcd 的函数,它接受参数ab返回它们的最大公约数。

4

20 回答 20

329

在标准库中。

>>> from fractions import gcd
>>> gcd(20,8)
4

inspectPython 2.7中模块的源代码:

>>> print inspect.getsource(gcd)
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

从 Python 3.5 开始,gcd math模块中;中的一个fractions已弃用。此外,inspect.getsource不再返回任何一种方法的解释性源代码。

于 2012-06-24T05:19:03.857 回答
42

具有 mn 的算法可以运行很长时间。

这个表现要好得多:

def gcd(x, y):
    while y != 0:
        (x, y) = (y, x % y)
    return x
于 2013-09-22T13:13:27.133 回答
18

这个版本的代码使用欧几里得算法来寻找 GCD。

def gcd_recursive(a, b):
    if b == 0:
        return a
    else:
        return gcd_recursive(b, a % b)
于 2015-02-20T16:21:16.050 回答
16
gcd = lambda m,n: m if not n else gcd(n,m%n)
于 2015-11-02T08:48:22.737 回答
5

使用递归

def gcd(a,b):
    return a if not b else gcd(b, a%b)

使用while

def gcd(a,b):
  while b:
    a,b = b, a%b
  return a

使用 lambda,

gcd = lambda a,b : a if not b else gcd(b, a%b)

>>> gcd(10,20)
>>> 10
于 2019-01-31T08:16:54.317 回答
2
def gcd(m,n):
    return gcd(abs(m-n), min(m, n)) if (m-n) else n
于 2013-06-29T05:48:21.810 回答
2

使用递归的非常简洁的解决方案:

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a%b)
于 2018-05-16T12:02:23.287 回答
1
def gcdRecur(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    # Base case is when b = 0
    if b == 0:
        return a

    # Recursive case
    return gcdRecur(b, a % b)
于 2013-11-15T09:56:58.383 回答
1
a=int(raw_input('1st no \n'))
b=int(raw_input('2nd no \n'))

def gcd(m,n):
    z=abs(m-n)
    if (m-n)==0:
        return n
    else:
        return gcd(z,min(m,n))


print gcd(a,b)

基于欧几里得算法的不同方法。

于 2013-06-29T04:51:29.113 回答
1

我认为另一种方法是使用递归。这是我的代码:

def gcd(a, b):
    if a > b:
        c = a - b
        gcd(b, c)
    elif a < b:
        c = b - a
        gcd(a, c)
    else:
        return a
于 2015-10-27T14:13:54.257 回答
0

在带有递归的python中:

def gcd(a, b):
    if a%b == 0:
        return b
    return gcd(b, a%b)
于 2014-07-27T20:54:55.863 回答
0
def gcd(a,b):
    if b > a:
        return gcd(b,a)
    r = a%b
    if r == 0:
        return b
    return gcd(r,b)
于 2014-12-03T19:41:46.683 回答
0

对于a>b

def gcd(a, b):

    if(a<b):
        a,b=b,a
        
    while(b!=0):
        r,b=b,a%r
        a=r
    return a

对于a>ba<b

def gcd(a, b):

    t = min(a, b)

    # Keep looping until t divides both a & b evenly
    while a % t != 0 or b % t != 0:
        t -= 1

    return t
于 2015-01-25T17:55:28.103 回答
0

我不得不使用 while 循环为家庭作业做这样的事情。不是最有效的方法,但如果你不想使用这个函数:

num1 = 20
num1_list = []
num2 = 40
num2_list = []
x = 1
y = 1
while x <= num1:
    if num1 % x == 0:
        num1_list.append(x)
    x += 1
while y <= num2:
    if num2 % y == 0:
        num2_list.append(y)
    y += 1
xy = list(set(num1_list).intersection(num2_list))
print(xy[-1])
于 2019-04-16T16:21:52.843 回答
0
def _grateest_common_devisor_euclid(p, q):
    if q==0 :
        return p
    else:
        reminder = p%q
        return _grateest_common_devisor_euclid(q, reminder)

print(_grateest_common_devisor_euclid(8,3))
于 2019-06-07T16:24:12.567 回答
-1

此代码根据用户给出的选择计算两个以上数字的 gcd,这里用户给出数字

numbers = [];
count = input ("HOW MANY NUMBERS YOU WANT TO CALCULATE GCD?\n")
for i in range(0, count):
  number = input("ENTER THE NUMBER : \n")
  numbers.append(number)
numbers_sorted = sorted(numbers)
print  'NUMBERS SORTED IN INCREASING ORDER\n',numbers_sorted
gcd = numbers_sorted[0]

for i in range(1, count):
  divisor = gcd
  dividend = numbers_sorted[i]
  remainder = dividend % divisor
  if remainder == 0 :
  gcd = divisor
  else :
    while not remainder == 0 :
      dividend_one = divisor
      divisor_one = remainder
      remainder = dividend_one % divisor_one
      gcd = divisor_one

print 'GCD OF ' ,count,'NUMBERS IS \n', gcd
于 2013-06-08T00:05:33.440 回答
-1

价值交换对我来说效果不佳。所以我只是为在 a < b 或 a > b 中输入的数字设置了一个类似镜像的情况:

def gcd(a, b):
    if a > b:
        r = a % b
        if r == 0:
            return b
        else:
            return gcd(b, r)
    if a < b:
        r = b % a
        if r == 0:
            return a
        else:
            return gcd(a, r)

print gcd(18, 2)
于 2013-06-18T20:03:52.170 回答
-2
#This program will find the hcf of a given list of numbers.

A = [65, 20, 100, 85, 125]     #creates and initializes the list of numbers

def greatest_common_divisor(_A):
  iterator = 1
  factor = 1
  a_length = len(_A)
  smallest = 99999

#get the smallest number
for number in _A: #iterate through array
  if number < smallest: #if current not the smallest number
    smallest = number #set to highest

while iterator <= smallest: #iterate from 1 ... smallest number
for index in range(0, a_length): #loop through array
  if _A[index] % iterator != 0: #if the element is not equally divisible by 0
    break #stop and go to next element
  if index == (a_length - 1): #if we reach the last element of array
    factor = iterator #it means that all of them are divisibe by 0
iterator += 1 #let's increment to check if array divisible by next iterator
#print the factor
print factor

print "The highest common factor of: ",
for element in A:
  print element,
print " is: ",

best_common_devisor(A)

于 2015-03-25T16:23:41.183 回答
-2
def gcdIter(a, b):
gcd= min (a,b)
for i in range(0,min(a,b)):
    if (a%gcd==0 and b%gcd==0):
        return gcd
        break
    gcd-=1
于 2018-05-25T12:47:31.967 回答
-2

这是实现概念的解决方案Iteration

def gcdIter(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    if a > b:
        result = b
    result = a

    if result == 1:
        return 1

    while result > 0:
        if a % result == 0 and b % result == 0:
            return result
        result -= 1
于 2019-02-15T21:40:31.607 回答