最大公约数gcd()

583 阅读1分钟

gcd()函数--Python

最大公约数或gcd是找到最大数的数学表达式,该数学数可以将必须找到gcd的两个数相除,结果余数为零。它具有许多数学应用程序。Python在math模块中具有内置的gcd函数,可用于此目的。

gcd()

它接受两个整数作为参数,并返回作为gcd值的整数。

语法

Syntax: gcd(x,y)
Where x and y are positive integers.

实现

使用递归的方式实现最大公约数
import sys
 
def gcd(a,b):
    if a%b == 0:
        return b
    else :
        return gcd(b,a%b)

gcd()的示例

在下面的示例中,我们打印出一对整数的gcd结果。

import math
print ("GCD of 75 and 30 is ",math.gcd(7530))
print ("GCD of 0 and 12 is ",math.gcd(012))
print ("GCD of 0 and 0 is ",math.gcd(00))
print ("GCD of -24 and -18 is ",math.gcd(-24-18))

输出结果

运行上面的代码给我们以下结果-

GCD of 75 and 30 is 15
GCD of 0 and 12 is 12
GCD of 0 and 0 is 0
GCD of -24 and -18 is 6