Python中的gcd()

最高公因数(HCF),也称为gcd,可以在python中使用 数学 模块,因此在许多情况下可以使任务更容易。

null
计算gcd的简单方法

  1. 使用 递归 :
  2. # Python code to demonstrate naive
    # method to compute gcd ( recursion )
    def hcfnaive(a,b):
    if (b = = 0 ):
    return a
    else :
    return hcfnaive(b,a % b)
    a = 60
    b = 48
    # prints 12
    print ( "The gcd of 60 and 48 is : " ,end = "")
    print (hcfnaive( 60 , 48 ))

    
    

    输出:

    The gcd of 60 and 48 is : 12
    

  3. 使用 循环
  4. # Python code to demonstrate naive
    # method to compute gcd ( Loops )
    def computeGCD(x, y):
    if x > y:
    small = y
    else :
    small = x
    for i in range ( 1 , small + 1 ):
    if ((x % i = = 0 ) and (y % i = = 0 )):
    gcd = i
    return gcd
    a = 60
    b = 48
    # prints 12
    print ( "The gcd of 60 and 48 is : " ,end = "")
    print (computeGCD( 60 , 48 ))

    
    

    输出:

    The gcd of 60 and 48 is : 12
    

  5. 使用 欧几里德算法

    # Python code to demonstrate naive
    # method to compute gcd ( Euclidean algo )
    def computeGCD(x, y):
    while (y):
    x, y = y, x % y
    return x
    a = 60
    b = 48
    # prints 12
    print ( "The gcd of 60 and 48 is : " ,end = "")
    print (computeGCD( 60 , 48 ))

    
    

    输出:

    The gcd of 60 and 48 is : 12
    

    使用数学。Python的gcd()函数

    使用gcd()只需一行就可以计算相同的gcd。

    math.gcd( x, y )
    Parameters : 
    x :  Non-negative integer whose gcd has to be computed.
    y : Non-negative integer whose gcd has to be computed.
    Return Value : 
    This method will return an absolute/positive integer value after 
    calculating the GCD of given parameters x and y.
    Exceptions : 
    When Both x and y are 0, function returns 0, If any number is a character ,
    Type error is raised.
    

    # Python code to demonstrate gcd()
    # method to compute gcd
    import math
    # prints 12
    print ( "The gcd of 60 and 48 is : " ,end = "")
    print (math.gcd( 60 , 48 ))

    
    

    输出:

    The gcd of 60 and 48 is : 12
    

    常见例外

    此功能中的一些常见例外情况包括:

    • 两个数字都是0,gcd都是0
    • 如果两个数字中只有一个不是数字,则会引发类型错误。

    # Python code to demonstrate gcd()
    # method exceptions
    import math
    # prints 0
    print ( "The gcd of 0 and 0 is : " ,end = "")
    print (math.gcd( 0 , 0 ))
    # Produces error
    print ( "The gcd of a and 13 is : " ,end = "")
    print (math.gcd( 'a' , 13 ))

    
    

    输出:

    The gcd of 0 and 0 is : 0
    The gcd of a and 13 is : 
    

    运行时错误:

    Traceback (most recent call last):
      File "/home/94493cdfb3c8509146254862d12bcc97.py", line 12, in 
        print (math.gcd('a',13))
    TypeError: 'str' object cannot be interpreted as an integer
    

    本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

    如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享