Python基于递归算法求最小公倍数和最大公约数示例

您所在的位置:网站首页 递归求阶层 Python基于递归算法求最小公倍数和最大公约数示例

Python基于递归算法求最小公倍数和最大公约数示例

2023-04-14 11:19| 来源: 网络整理| 查看: 265

瞧,那夕阳边的云霞,好似得到了夕阳的赏赐,变得欣喜异常,时而围坐一团,倾诉衷肠;时而围着夕阳跳起了探戈;更有自我陶醉的,远离他人,自我欣赏……

本文实例讲述了Python基于递归算法求最小公倍数和最大公约数。分享给大家供大家参考,具体如下:

# 最小公倍数 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

PS:这里再为大家推荐一款本站相关在线工具供大家参考:

在线最小公倍数/最大公约数计算工具: http://tools.haodaima.com/jisuanqi/gbs_gys_calc

希望本文所述对大家Python程序设计有所帮助。

以上就是Python基于递归算法求最小公倍数和最大公约数示例。永远比对手快一步。更多关于Python基于递归算法求最小公倍数和最大公约数示例请关注haodaima.com其它相关文章!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3