Python实现Project Euler 5
来源:互联网 发布:php发展前景 编辑:程序博客网 时间:2024/05/21 00:18
首先,来看题:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
将sum分解成多个质因子,并计算每个质因子出现的次数,而对于新增的i,也分解成多个质因子,看需要多少个怎样的质因子,与sum的相比较,如果质因子个数小于i所需要的, 则乘以这个质因子相差的个数次幂,而个数大于或等于的,则说明出现的i是可以被sum整除的,(下面的prime方法,返回一个字典类型数据,键存的是质因子,值则是出现的次数),代码如下:
# coding:utf-8# Desc : Project Euler 5# Author : Tina# Date : 2015-09-02# 其实就是求最小公倍数def prime(sum): arr = {} n = 2 while(n <= sum): a = 0 while(sum%n == 0): a = a+1 sum = sum/n if(a>0): arr[n] = a #质因子累计a次 n = n+1 return arrimport timesum = 1n = int(raw_input())start_time = time.clock() for i in range(2, n): dicsum = prime(sum) dici = prime(i) for x in dici.keys(): if(dicsum.get(x,0) < dici[x]): count = dici[x] - dicsum.get(x,0) sum = sum*(x**count)print sumend_time = time.clock()print end_time-start_time
后来想起来,以前有用PHP写过这个题目的,就翻出来看了看,发现上面的想法太绕了,求最小公倍数,其实可以这样,首先求得两者的最大公约数,两者相乘再除以最大公约数,即可得到两者的最小公倍数!不说了,说多了都是泪,绕了一大圈,看代码:
# coding:utf-8# Desc : Project Euler 5# Author : Tina# Date : 2015-09-02import timen = int(raw_input())start_time = time.clock()sum = 1for i in range(1, n): k = i tsum = sum #辗转相除法,得到两者最大公约数k while(tsum%k != 0): t = k k = tsum%k tsum = t sum = sum*i/kprint sumend_time = time.clock()print end_time-start_time
顺便截图一张两者的效率之比:
当达到2000时,红色的运行时间的对比:
现在觉得Python的计算能力太强大了,相比之下PHP的计算能力真不咋地,PHP的运行到25后就溢出了,变成了负数……,另外还是附上PHP的代码:
/** * @ Desc : Project Euler 5 * @ Author : Tina * @ Date : 2015-09-02 */ function project5($n) { $sum = 1; for($i= 1;$i<=$n;$i++){ $k = $i; $tsum = $sum; //找到最大公约数,辗转相除法 while($tsum%$k !=0){ $t = $k; $k = $tsum%$k; $tsum = $t; } $sum = $sum*$i/$k; } echo $sum.'<br>'; } project5(20);
0 0
- Python实现Project Euler 5
- Project Euler Problems 19-22 Python实现
- Python-Project Euler 22
- Python-Project Euler 24
- Python-Project Euler 26
- Python-Project Euler 27
- Python-Project Euler 29
- Python-Project Euler 30
- Python-Project Euler 31
- Python-Project Euler 32
- Python-Project Euler 36
- Python-Project Euler 37
- Python-Project Euler 38
- Python-Project Euler 39
- Python-Project Euler 40
- Python-Project Euler 41
- Python-Project Euler 42
- Python-Project Euler 43
- 关于linux下的curl命令的使用
- 软件项目管理流程总结
- editiew 限制空格输入
- js中的递归函数
- php导出excel表格内部换行
- Python实现Project Euler 5
- Oracle timestamp
- android的顶部操作栏
- iOS 定位 点击设置->隐私->定位 闪退的问题
- iOS Sqlite 增删改查基本操作
- HIbernate注解详解
- linux命令--------------netstat
- ACM/ICPC 14 北京站现场赛 B
- 软工视频第一章——开门见山