Python 中最大公约数的代码[关闭]

2025-04-16 08:57:00
admin
原创
18
摘要:问题描述:a 和 b 的最大公约数 (GCD) 是能整除它们且无余数的最大数。求两个数的最大公约数 (GCD) 的一种方法是欧几里得算法,该算法基于这样的观察:如果是除以 的r余数,则。作为基准情况,我们可以使用。a`bgcd(a, b) = gcd(b, r)gcd(a, 0) = a`编写一个名为 gcd...

问题描述:

a 和 b 的最大公约数 (GCD) 是能整除它们且无余数的最大数。

求两个数的最大公约数 (GCD) 的一种方法是欧几里得算法,该算法基于这样的观察:如果是除以 的r余数,则。作为基准情况,我们可以使用。a`bgcd(a, b) = gcd(b, r)gcd(a, 0) = a`

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


解决方案 1:

它在标准库中。

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

Python 2.7 中模块的源代码inspect

>>> 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不再返回任何方法的解释性源代码。

解决方案 2:

具有 mn 的算法运行时间可能非常长。

这个表现更好:

def gcd(x, y):
    while y != 0:
        (x, y) = (y, x % y)
    return x

解决方案 3:

此版本的代码利用欧几里得算法来查找 GCD。

def gcd_recursive(a, b):
    if b == 0:
        return a
    else:
        return gcd_recursive(b, a % b)

解决方案 4:

gcd = lambda m,n: m if not n else gcd(n,m%n)

解决方案 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

解决方案 6:

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

解决方案 7:

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

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a%b)

解决方案 8:

a=int(raw_input('1st no 
'))
b=int(raw_input('2nd no 
'))

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)

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

解决方案 9:

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)

解决方案 10:

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

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

解决方案 11:

在python中使用递归:

def gcd(a, b):
    if a%b == 0:
        return b
    return gcd(b, a%b)

解决方案 12:

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

解决方案 13:

为了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

解决方案 14:

我在家庭作业中用 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])

解决方案 15:

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))

解决方案 16:

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

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

解决方案 17:

值交换对我来说不太好用。所以我就为在 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)

解决方案 18:

#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: ",

最大共同因素(A)

解决方案 19:

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

解决方案 20:

以下是实现以下概念的解决方案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
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2482  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1533  
  PLM(产品生命周期管理)项目对于企业优化产品研发流程、提升产品质量以及增强市场竞争力具有至关重要的意义。然而,在项目推进过程中,范围蔓延是一个常见且棘手的问题,它可能导致项目进度延迟、成本超支以及质量下降等一系列不良后果。因此,有效避免PLM项目范围蔓延成为项目成功的关键因素之一。以下将详细阐述三大管控策略,助力企业...
plm系统   0  
  PLM(产品生命周期管理)项目管理在企业产品研发与管理过程中扮演着至关重要的角色。随着市场竞争的加剧和产品复杂度的提升,PLM项目面临着诸多风险。准确量化风险优先级并采取有效措施应对,是确保项目成功的关键。五维评估矩阵作为一种有效的风险评估工具,能帮助项目管理者全面、系统地评估风险,为决策提供有力支持。五维评估矩阵概述...
免费plm软件   0  
  引言PLM(产品生命周期管理)开发流程对于企业产品的全生命周期管控至关重要。它涵盖了从产品概念设计到退役的各个阶段,直接影响着产品质量、开发周期以及企业的市场竞争力。在当今快速发展的科技环境下,客户对产品质量的要求日益提高,市场竞争也愈发激烈,这就使得优化PLM开发流程成为企业的必然选择。缺陷管理工具和六西格玛方法作为...
plm产品全生命周期管理   0  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用