溫馨提示×

怎么用python求最大公約數(shù)

小億
315
2023-09-28 11:26:41
欄目: 編程語言

你可以使用以下兩種方式來使用Python求最大公約數(shù):

方法一:使用循環(huán)迭代的方式

def gcd(a, b):
while b:
a, b = b, a % b
return a
x = int(input("請輸入第一個數(shù):"))
y = int(input("請輸入第二個數(shù):"))
print("最大公約數(shù)是:", gcd(x, y))

方法二:使用遞歸的方式

def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
x = int(input("請輸入第一個數(shù):"))
y = int(input("請輸入第二個數(shù):"))
print("最大公約數(shù)是:", gcd(x, y))

以上兩種方式中,都是利用輾轉(zhuǎn)相除法求解最大公約數(shù)。第一種方式使用了循環(huán)迭代,每次都將較小的數(shù)賦值給b,較大的數(shù)取余后賦值給a,直到b為0。第二種方式使用了遞歸,將較小的數(shù)作為第一個參數(shù),較大的數(shù)取余作為第二個參數(shù),直到第二個參數(shù)為0。

0