Python基于递归算法求最小公倍数和最大公约数示例
作者:混沌鳄鱼 时间:2021-07-20 09:36:23
本文实例讲述了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.jb51.net/jisuanqi/gbs_gys_calc
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/xpresslink/article/details/78875473
标签:Python,递归算法,最小公倍数,最大公约数


猜你喜欢
python由已知数组快速生成新数组的方法
2022-11-01 09:08:36
常见Dreamweaver使用过程中的问题及解决办法
2011-03-17 16:16:00
利用Python编写个有趣的记仇本
2022-08-25 19:20:20

提升设计品质的8个布局方案[译]
2010-03-18 16:06:00

PHP实现简单注册登录系统
2024-05-02 17:34:13

pygame实现俄罗斯方块游戏(AI篇2)
2022-03-02 13:03:10

python爬取Ajax动态加载网页过程解析
2023-05-15 15:51:47
将MySQL的临时目录建立在内存中的教程
2024-01-25 20:42:40
golang中值类型/指针类型的变量区别总结
2023-09-02 15:07:11
讲解SQL Server安装sp4补丁报错的解决方法
2009-04-11 17:39:00
Golang断言判断值类型的实现方法
2024-02-16 09:59:38

MySQL慢SQL语句常见诱因以及解决方法
2024-01-18 12:36:25
MySQL事务管理的作用详解
2024-01-23 21:20:37

Python直接赋值与浅拷贝和深拷贝实例讲解使用
2021-06-16 08:21:21

IE6终极备忘单——对IE6单独兼容[译]
2010-01-21 18:34:00
关于《回访确认》的几个问题
2009-08-24 12:43:00
C# SQLite数据库入门使用说明
2024-01-25 20:01:20

MySQL全局共享内存介绍
2024-01-14 09:40:14
SQL Server新特性SequenceNumber用法介绍
2024-01-15 02:38:34

python爬虫用request库处理cookie的实例讲解
2023-07-26 03:57:53