【发布时间】:2016-08-12 15:59:19
【问题描述】:
我是编码新手,并尝试进行项目欧拉练习以提高我的编码知识。关于 Project Euler #2,我遇到了几种解决方案。
但是,与我找到的解决方案相比,我想知道为什么我的代码需要更长的时间来计算。
如果有人能指导我了解两者之间的区别,我将不胜感激。
我的代码:
def fib(n):
if n==0:
return 0
elif n == 1:
return 1
else:
f=fib(n-1)+fib(n-2)
return f
i=0
store=[]
while fib(i)<=4000000:
i += 1
if fib(i)%2 == 0:
store.append(fib(i))
print('The total is: '+str(sum(store)))
我找到的在线解决方案:
a = 1
b = 2
s = 0
while b <= 4000000:
if not b % 2:
s += b
a, b = b, a + b
print(s)
【问题讨论】:
-
与任何答案无关,但您可以通过从偶数斐波那契跳到偶数斐波那契来进一步改进迭代解决方案,这样您就可以摆脱 if 语句。每个第 3 个斐波那契数都是偶数,因此连续应用该规则 3 次:
while b < 4000000: s += b; a, b = a+2*b, 2*a+3*b。 -
您发布的程序无效;请修正你的缩进。
标签: python python-3.x fibonacci