Python实现的求解最小公倍数算法示例
作者:grey_csdn 时间:2022-12-11 04:50:03
本文实例讲述了Python实现的求解最小公倍数算法。分享给大家供大家参考,具体如下:
简单分析了一下,前面介绍的最大公约数的求解方法跟最小公倍数求解方法类似,只需要改一个简单的条件,然后做一点简单的其他计算。问题的解决也是基于分解质因式的程序。
程序实现以及测试case代码如下:
#!/usr/bin/python
from collections import Counter
def PrimeNum(num):
r_value =[]
for i in range(2,num+1):
for j in range(2,i):
if i % j == 0:
break
else:
r_value.append(i)
return r_value
def PrimeFactorSolve(num,prime_list):
for n in prime_list:
if num % n == 0:
return [n,num / n]
def PrimeDivisor(num):
num_temp =num
prime_range= PrimeNum(num)
ret_value =[]
while num not in prime_range:
factor_list= PrimeFactorSolve(num,prime_range)
ret_value.append(factor_list[0])
num =factor_list[1]
else:
ret_value.append(num)
return Counter(ret_value)
def LeastCommonMultiple(num1,num2):
dict1 =PrimeDivisor(num1)
dict2 =PrimeDivisor(num2)
least_common_multiple= 1
for key in dict1:
if key in dict2:
if dict1[key] > dict2[key]:
least_common_multiple*= (key ** dict1[key])
else:
least_common_multiple*= (key ** dict2[key])
for key in dict1:
if key not in dict2:
least_common_multiple*= (key ** dict1[key])
for key in dict2:
if key not in dict1:
least_common_multiple*= (key ** dict2[key])
return least_common_multiple
print(LeastCommonMultiple(12,18))
print(LeastCommonMultiple(7,2))
print(LeastCommonMultiple(7,13))
print(LeastCommonMultiple(24,56))
print(LeastCommonMultiple(63,81))
程序执行结果:
E:\WorkSpace\01_编程语言\03_Python\math>pythonleast_common_multiple.py
36
14
91
168
567
通过验证,计算结果准确。
PS:这里再为大家推荐一款本站相关在线工具供大家参考:
在线最小公倍数/最大公约数计算工具:
http://tools.jb51.net/jisuanqi/gbs_gys_calc
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/grey_csdn/article/details/71429966
标签:Python,最小公倍数,算法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python logging简介详解
2022-05-12 09:27:02
Python排序搜索基本算法之归并排序实例分析
2023-10-19 04:15:11
![](https://img.aspxhome.com/file/2023/7/98897_0s.jpg)
PHP多种序列化/反序列化的方法详解
2024-04-30 08:47:55
setInterval 和 setTimeout 会产生内存溢出
2008-03-08 13:10:00
详解Python自建logging模块
2023-12-21 02:28:50
一文学会Mysql数据库备份与恢复
2024-01-26 10:17:08
![](https://img.aspxhome.com/file/2023/4/114964_0s.jpg)
浅谈在django中使用filter()(即对QuerySet操作)时踩的坑
2022-05-03 10:24:49
![](https://img.aspxhome.com/file/2023/6/101736_0s.jpg)
对Python中内置异常层次结构详解
2023-10-18 11:08:49
python高级特性和高阶函数及使用详解
2022-09-17 20:13:50
![](https://img.aspxhome.com/file/2023/4/121104_0s.png)
python获取当前计算机cpu数量的方法
2023-08-01 14:20:03
Golang实现短网址/短链服务的开发笔记分享
2024-02-08 15:37:18
MySQL性能全面优化方法参考,从CPU,文件系统选择到mysql.cnf参数优化
2024-01-22 16:37:20
Python实现单例模式的五种写法总结
2022-09-07 08:34:11
八种获取当前日期的js代码
2007-09-07 10:26:00
Mysql主从数据库(Master/Slave)同步配置与常见错误
2024-01-21 17:48:35
![](https://img.aspxhome.com/file/2023/1/115271_0s.png)
python爬虫基础之简易网页搜集器
2023-08-25 14:05:17
![](https://img.aspxhome.com/file/2023/1/88851_0s.png)
MySQL5.6 Replication主从复制(读写分离) 配置完整版
2024-01-18 05:38:41
asp分类算法要解决的问题
2009-09-10 16:49:00
深入SQL Server中char、varchar、text和nchar、nvarchar、ntext的区别详解
2024-01-26 11:26:57
ASP 读取MP3文件帧的信息比特率,采样频率,播放时间
2010-06-04 12:22:00