2015-04-01 41 views
3

我試圖解決使用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) 

任何建議將受到歡迎。

+6

你有一個無限循環,'n'永遠不會從零遞增。 – miradulo 2015-04-01 15:30:29

+0

也不要爲每個術語遞歸地重新計算。使用發電機或其他東西。 – cmd 2015-04-01 15:35:10

+0

[斐波那契數列的有效計算]的可能重複(http://stackoverflow.com/questions/18172257/efficient-calculation-of-fibonacci-series) – greybeard 2015-04-19 17:36:45

回答

3

由於n從零開始在while循環中從零開始增加,因此會產生無限循環。此外,爲什麼不總結你的斐波那契總以及發現在同一while循環的下一個斐波那契值,就像這樣:

x= 1 
y=1 
total = 0 
while x <= 4000000: 
    if x % 2 == 0: 
     total += x 
    x, y = y, x + y  
print (total) 

輸出:

4613732 
+0

對不起,我只是要問同樣的問題,因此取消選中回答。感謝您的澄清。 – 2015-04-01 15:50:38

+0

@DavidClark不用擔心,很高興我能幫上忙。 – miradulo 2015-04-01 15:50:52

0

您也可以使用發電機並添加號碼

def fib(): 
    a, b = 0, 1 
    while 1: 
     yield a 
     a, b = b, a + b 

f = fib() 
total = 0 
while total <= 4000000: 
    current = f.next() 
    if current % 2 == 0: 
     total += current 

print total 
0

因爲這看起來像一個家庭作業分配,我把一些有趣的Python

from math import sqrt 
# Using Binet's formula 
def fib(n): 
    return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))) 

def sum_even_terms(limit = 4000000): 
    n = total = 0 
    while True: 
     term = fib(n) 
     n += 1 
     if term > limit: break 
     if term % 2 == 0: 
      total += term 
    return total 

print sum_even_terms() 

def is_nth_term_even(n): 
    return (fib(n) % 2 == 0) 

print is_nth_term_even(30) 
1

只是爲了好玩,這裏是一個非常簡短的解決方案:

def fib_even_sum(limit=4*10**6): 
    """Sum of the even Fibonacci numbers up to the given limit.""" 
    b, c = 1, 2 
    while c <= limit: 
     a = b + c; b = c + a; c = a + b 
    return b // 2 

print fib_even_sum() # outputs 4613732 

它是基於以下事實:

  1. 三分之一的斐波那契數甚至。

  2. 如果Fib(n)是偶數,則高達Fib(n)所述的甚至斐波那契數之和等於所述奇數斐波那契數高達Fib(n)總和(因爲每個偶數斐波那契數是兩個的總和在奇數斐波那契數字之前)。

  3. 所有斐波納契數字(偶數和奇數)以及包括Fib(n)的總和爲Fib(n+2) - 1(通過歸納證明)。

所以如果Fib(n)被列入總和的最後偶數,那麼 你想要的總只是(Fib(n+2) - 1)/2

+0

這很聰明,+1 – miradulo 2015-04-01 19:54:24