python 求最大公约数
时间: 2023-11-02 08:00:38 浏览: 83
最大公约数可以使用多种方法进行求解。其中,常见的方法有暴力枚举法、辗转相除法和更相减损术。在Python中,我们可以使用以下代码来求两个数的最大公约数:
1. 暴力枚举法:
def get_greatest_common_divisor(a, b):
big = max(a, b)
small = min(a, b)
if big % small == 0:
return small
for i in range(small // 2, 1, -1):
if small % i == 0 and big % i == 0:
return i
return 1
print(get_greatest_common_divisor(26, 13))
2. 辗转相除法:
def get_greatest_common_divisor_V2(a, b):
big = max(a, b)
small = min(a, b)
if big % small == 0:
return small
return get_greatest_common_divisor_V2(big % small, small)
print(get_greatest_common_divisor_V2(26, 13))
3. 更相减损术:
def get_greatest_common_divisor_V3(a, b):
if a == b:
return a
big = max(a, b)
small = min(a, b)
return get_greatest_common_divisor_V3(big - small, small)
print(get_greatest_common_divisor_V3(26, 13))
以上任何一种方法都可以求解最大公约数,根据具体的需求和情况选择合适的方法即可。