一、基于枚举算法
#最大公约数gcd
a, b = map(int, input('请输入两个数字,其间用空格隔开:').split())
gcd=a if a<=b else b
while gcd>0:
if a%gcd==0 and b%gcd==0:
print(f" {a} 和 {b} 的最大公约数为:{gcd}")
break
else:
gcd-=1
#最小公倍数lcm:
a, b = map(int, input('请输入两个数字,其间用空格隔开:').split())
lcm = a if a>=b else b
while True:
if lcm%a==0 and lcm%b==0:
print(f"{a} 和 {b} 的最小公倍数为:{lcm}")
break
else:
lcm+=1
#最小公倍数lcm:
a, b = map(int, input('请输入两个数字,其间用空格隔开:').split())
def lcm(a,b):
a,b = (a,b) if a>=b else (b,a)
c=1
while c<=b:
if a*c%b==0:
return a*c
else:
c+=1
print(f"{a} 和 {b} 的最小公倍数为:{lcm(a,b}")
二、基于递归算法
#递归算法求最大公约数:
def gcd(a,b):
a,b=(a,b) if a>=b else (b,a)
if a==b:
return a
elif a-b>b:
return gcd(a-b,b)
else:
return gcd(b,a-b)
test_cases=[(35,14),(88,66),(5,4),(20,10),(5,15)]
for case in test_cases:
print("GCD of {} and {} is {}".format(*case,gcd(*case)))
#最小公倍数lcm:
def lcm(a,b,c=1):
a,b=(a,b) if a>=b else (b,a)
if a*c%b != 0:
return lcm(a,b,c+1)
else:
return a*c
test_cases=[(4,8),(35,42),(5,7),(20,10)]
for case in test_cases:
print("lcm of {} and {} is {}".format(*case,lcm(*case)))
#最小公倍数lcm:
def lcm(a,b):
for i in range(min(a,b),2,-1):
if a%i==0 and b%i==0: #求取最大公约数i
return i*lcm(a//i,b//i)
else:
return a*b
test_cases=[(4,8),(35,42),(5,7),(20,10)]
for case in test_cases:
print("lcm of {} and {} is {}".format(*case,lcm(*case)))