Python 最大公约数算法

Python3 实例

以下代码用于实现最大公约数算法:

实例(Python 3.0+)

# -*- coding: UTF-8 -*-

# Filename : hcf.py
# author by : www.runoops.com
# Python 两个数的最大公约数

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))

执行以上代码输出结果为:

$ python hcf.py
输入第一个数字: 4
输入第二个数字: 9
4 和 9 的最大公约数为 1

Python3 实例