Python递归实现最大公约数与最小公倍数算法详解
本文介绍使用Python递归算法计算最大公约数(GCD)和最小公倍数(LCM)的方法。通过定义递归函数,分别处理数值整除与余数判断逻辑,并附带多组测试用例验证结果。文章同时提供了在线计算工具链接及Python相关学习资源,适合初学者理解递归在数学运算中的应用。
本文通过具体示例,展示如何利用Python的递归算法来计算两个数的最小公倍数(LCM)和最大公约数(GCD)。内容包含代码实现及运行结果,供读者参考学习。
# 最小公倍数
def lcm(a, b, c=1):
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 {} & {} is {}'.format(*case, lcm(*case)))
def lcm(a, b):
for i in range(2, min(a,b)+1):
if a % i == 0 and b % i == 0:
return i * lcm(a//i, b//i)
else:
return a*b
test_cases = [(4, 8), (5, 7), (24, 16), (35, 42)]
for case in test_cases:
print('lcm of {} & {} is {}'.format(*case, lcm(*case)))
# 最大公约数
def gcd(a, b):
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)]
for case in test_cases:
print('GCD of {} & {} is {}'.format(*case, gcd(*case)))
程序执行后的输出结果如下所示:
lcm of 4 & 8 is 8 lcm of 35 & 42 is 210 lcm of 5 & 7 is 35 lcm of 20 & 10 is 20 GCD of 35 & 14 is 7 GCD of 88 & 66 is 22 GCD of 5 & 4 is 1 GCD of 20 & 10 is 10
此外,推荐一款本站提供的在线辅助工具,方便用户快速进行相关计算:
在线最小公倍数/最大公约数计算工具: http://tools.jb51.net/jisuanqi/gbs_gys_calc
如需深入了解Python编程技巧,建议查阅本站以下专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》。
希望上述内容能对您的Python程序设计有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













