Python 最大公約數演算法
以下代碼用於實現最大公約數演算法:
實例(Python 3.0+)
# Filename : test.py
# author by : www.xuhuhu.com
# 定義一個函數
def hcf(x, y):
"""該函數返回兩個數的最大公約數"""
# 獲取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
# 用戶輸入兩個數字
num1 = int(input("輸入第一個數字: "))
num2 = int(input("輸入第二個數字: "))
print( num1,"和", num2,"的最大公約數為", hcf(num1, num2))
執行以上代碼輸出結果為:
輸入第一個數字: 54 輸入第二個數字: 24 54 和 24 的最大公約數為 6