计算最大公约数(暴力求解和辗转相除法)
方法一:暴力求解
def hcf(x,y):
smaller = x if x<y else y
for ii in range(1,smaller+1):
if x%ii==0 and y%ii==0:
max_hcf=ii
else:
pass
return max_hcf
print(hcf(35,56))
方法二:辗转相除法
基本逻辑为不断计算两个数的余数
'''辗转相除法计算最大公约数'''
'''
计算过程 list
24,45 45,24
45%24 = 21 45,24,21
24,21
24%21 = 3 45,24,21,3
21,3
21%3 = 0 45,24,21,3,0
'''
def hcf(x,y):
list = sorted([x,y], reverse = True)
while(list[-1]!=0):
list.append(list[-2]%list[-1])
else:
return list[-2]
print(hcf(24,45))
计算最小公倍数
方法一:暴力求解
def lcm(x,y):
larger = x if x>y else y
while True:
if larger%x==0 and larger%y==0:
min_lcm = larger
return larger
else:
larger += 1
print(lcm(24,45))
方法二:利用辗转相除法中的部分结论
def hcf(x,y):
list = sorted([x,y], reverse = True) # 从大到小排列
while(list[-1]!=0):
list.append(list[-2]%list[-1])
else:
return list[-2]
def lcm(x,y):
return x*y//hcf(x,y)
print(hcf(24,45))
print(lcm(24,45))
运行结果
3
360
Process finished with exit code 0
Python实现最大公约数和最小公倍数计算
该博客介绍了如何使用Python编程计算两个数的最大公约数(暴力求解和辗转相除法)以及最小公倍数,详细讲解了两种不同的计算方法,并提供了运行结果。
1万+





