project Euler第五题

15 篇文章 0 订阅
11 篇文章 0 订阅

题目:

2520is the smallest number that can be divided by each of the numbersfrom 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbersfrom 1 to 20?


算法1:

#!/usr/bin/env python
#coding=utf-8
import time
start = time.time()

lst = [a for a in xrange(1,21)]
res = []
b = 1
i = 1
flag2 = True
while i<21:
    if flag2:
        i += 1
    flag = True
    flag2 = True
    for index,a in enumerate(lst):
        if a%i == 0:
            flag2 = False
            lst[index] = a/i
            if flag:
                res.append(i)
                flag = False

for a in res:
    b *=a

print b
print time.time() - start

这个方法就是上学时候学的用短除法求多个数最小公倍数的算法,效率比较低。


算法2:

#!/usr/bin/env python
#coding=utf-8
import time

start = time.time()
def gcd(m,n):
    if m<n:
        m,n = n,m
    while True:
        m,n = n,m%n
        if n == 0:
            return m
result = 2
def lcd(m,n):
    return m*n/gcd(m,n)
for i in xrange(3,21):
    result = lcd(i,result)
print result
print time.time() - start

这个算法也很简单,从2开始一个一个的求最小公倍数,速度上比上一个要快一些

结果:

算法1:232792560

0.00078010559082

算法2:232792560

0.000141859054565


从结果也可以明显看出算法2要比1效率高。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值