Project Euler每帖一题(005)

题目:
[quote]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?[/quote]

这个题目解得很差,写了个函数,传入1到10,速度还行,传入1到20,竟然计算了XX秒...看来算法太烂了,自我笔试下@@@@

我的python代码:
def gcd(list):
n = max(list)
flag = True
i = 1
while True:
for j in list:
if (n * i) % j != 0:
flag = False
break
if flag:
return n * i
else:
flag = True
i += 1

print gcd(range(1,21))


看了别人的解法,选了个比较大的基数,思路差不多:
i = 9699690 # Continuation.9699690=2*3*5*7*11*13*17*19
while 1:
print "Testing: %s" % i
for x in range(1, 21):
print "%s:" % x,
if i % x != 0:
print "Fail"
break
else:
print "Pass"
else:
print "Solution: %s" % i
break
i+=9699690


一种比较好的解决方案,核心思想是利用分解质因数来求解最大公倍数:
num = 20
'''
isSolved = False
i = 0
while not isSolved:
for ii in range(2,num+1):
if i % ii == 0 and i != 0:
if ii == num: isSolved = True
else:
i = i + num
break
print 'Lowest divisor: ', i
'''

def isPrime(a):
prime=True
for i in range(2,a):
if (a % i == 0): prime=False
if prime: return True
else: return False

factorz = []
primeFactorz = []
def getPrimeFactors(a):
gotFactor = False
for ii in range(2,a+1):
if a % ii == 0:
gotFactor = True
b = a/ii
if isPrime(ii): factors.append(ii)
else: getPrimeFactors(ii)
if isPrime(b) and b != 1: factors.append(b)
else: getPrimeFactors(b)
if gotFactor: break

for i in range(2,num+1):
factors=[]
getPrimeFactors(i)
factorz.append(factors)

print 'Printing Factors of 2 through', num
for i in factorz:
print i

new=[]
total=[]
def getHighestPow(a):
counthigh = 0
for i in factorz:
count = 0
for ii in i:
if ii == a:
count = count + 1
if count > counthigh:
counthigh = count
if a not in new:
new.append(a)
total.append(a**counthigh)

for i in factorz:
for ii in i:
getHighestPow(ii)

sum=1
for i in total:
sum = sum * i

print 'Lowest Common Multiple: ', sum
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值