Python3 執行個體
以下代碼用于實作最大公約數算法:
執行個體(Python 3.0+)
# Filename : test.py
# author by : www.runoob.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