您的位置:首页 > 编程语言 > Python开发

Python实现Project Euler 5

2015-09-02 10:02 549 查看
首先,来看题:

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
= a #质因子累计a次
n = n+1
return arr

import time
sum = 1
n = 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 sum
end_time = time.clock()
print end_time-start_time




后来想起来,以前有用PHP写过这个题目的,就翻出来看了看,发现上面的想法太绕了,求最小公倍数,其实可以这样,首先求得两者的最大公约数,两者相乘再除以最大公约数,即可得到两者的最小公倍数!不说了,说多了都是泪,绕了一大圈,看代码:

# coding:utf-8
# Desc : Project Euler 5
# Author : Tina
# Date : 2015-09-02
import time
n = int(raw_input())
start_time = time.clock()
sum = 1
for i in range(1, n):
k = i
tsum = sum
#辗转相除法,得到两者最大公约数k
while(tsum%k != 0):
t = k
k = tsum%k
tsum = t
sum = sum*i/k
print sum
end_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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: