求两个数的gcd的Python程序
给定两个数字。任务是找到两个数字的 GCD。
使用 STL :
在Python中, math 模块包含许多数学运算,可以使用该模块轻松执行。 math.gcd()函数计算其参数中提到的 2 个数字的最大公约数。
Syntax: math.gcd(x, y)
Parameter:
x : Non-negative integer whose gcd has to be computed.
y : Non-negative integer whose gcd has to be computed.
Returns: 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.
Python3
# Python code to demonstrate the working of gcd()
# importing "math" for mathematical operations
import math
# prints 12
print("The gcd of 60 and 48 is : ", end="")
print(math.gcd(60, 48))
Python3
# Python code to demonstrate naive
# method to compute gcd ( recursion )
def hcf(a, b):
if(b == 0):
return a
else:
return hcf(b, a % b)
a = 60
b = 48
# prints 12
print("The gcd of 60 and 48 is : ", end="")
print(hcf(60, 48))
Python3
# Recursive function to return gcd of a and b
def gcd(a, b):
# Everything divides 0
if (a == 0):
return b
if (b == 0):
return a
# base case
if (a == b):
return a
# a is greater
if (a > b):
return gcd(a-b, b)
return gcd(a, b-a)
# Driver program to test above function
a = 98
b = 56
if(gcd(a, b)):
print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
print('not found')
输出
The gcd of 60 and 48 is : 12
使用递归:
蟒蛇3
# Python code to demonstrate naive
# method to compute gcd ( recursion )
def hcf(a, b):
if(b == 0):
return a
else:
return hcf(b, a % b)
a = 60
b = 48
# prints 12
print("The gcd of 60 and 48 is : ", end="")
print(hcf(60, 48))
输出
The gcd of 60 and 48 is : 12
使用欧几里得算法:
欧几里得算法(或欧几里得算法)是一种有效地找到两个数的最大公约数 (GCD) 的方法。两个整数 X 和 Y 的 GCD 是将 X 和 Y 整除的最大数(不留余数)。
算法伪代码-
- 设 a, b 为两个数
- 模 b = R
- 设 a = b 且 b = R
- 重复步骤 2 和 3,直到 a mod b 大于 0
- GCD = b
- 结束
蟒蛇3
# Recursive function to return gcd of a and b
def gcd(a, b):
# Everything divides 0
if (a == 0):
return b
if (b == 0):
return a
# base case
if (a == b):
return a
# a is greater
if (a > b):
return gcd(a-b, b)
return gcd(a, b-a)
# Driver program to test above function
a = 98
b = 56
if(gcd(a, b)):
print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
print('not found')
输出
GCD of 98 and 56 is 14