我試圖解決使用Python如下:使用斐波納契計劃,以即使和元素
在Fibonacci序列中的每個新名詞是通過將前兩個方面產生。通過用1和2開始,第一10項將是: 1,2,3,5,8,13,21,34,55,89,...
通過考慮在術語斐波納契數列的值不超過四百萬,找到偶數項的和。
到目前爲止,我已經能夠生成斐波那契元素,但試圖對偶數元素求和時,我的代碼似乎停滯不前。以下代碼如下:
def fib(n):
if n==0:
return 0
elif n==1:
return 1
if n>1:
return fib(n-1)+fib(n-2)
n=0
total=0
while fib(n)<=4000000:
if fib(n)%2==0:
total+=fib(n)
print(total)
任何建議將受到歡迎。
你有一個無限循環,'n'永遠不會從零遞增。 – miradulo 2015-04-01 15:30:29
也不要爲每個術語遞歸地重新計算。使用發電機或其他東西。 – cmd 2015-04-01 15:35:10
[斐波那契數列的有效計算]的可能重複(http://stackoverflow.com/questions/18172257/efficient-calculation-of-fibonacci-series) – greybeard 2015-04-19 17:36:45