Python 最大公約數(shù)算法

Document 對象參考手冊 Python3 實例

以下代碼用于實現(xiàn)最大公約數(shù)算法:

# Filename : test.py
# author by : www.o2fo.com

# 定義一個函數(shù)
def hcf(x, y):
   """該函數(shù)返回兩個數(shù)的最大公約數(shù)"""

   # 獲取最小值
   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


# 用戶輸入兩個數(shù)字
num1 = int(input("輸入第一個數(shù)字: "))
num2 = int(input("輸入第二個數(shù)字: "))

print( num1,"和", num2,"的最大公約數(shù)為", hcf(num1, num2))

執(zhí)行以上代碼輸出結(jié)果為:

輸入第一個數(shù)字: 54
輸入第二個數(shù)字: 24
54 和 24 的最大公約數(shù)為 6

Document 對象參考手冊 Python3 實例