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

Document 對(duì)象參考手冊(cè) Python3 實(shí)例

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

# Filename : test.py
# author by : eska-fuses.cn

# 定義一個(gè)函數(shù)
def hcf(x, y):
   """該函數(shù)返回兩個(gè)數(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


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

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

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

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

Document 對(duì)象參考手冊(cè) Python3 實(shí)例