簡體   English   中英

使用Fibonacci程序求和偶數元素

[英]Using Fibonacci Program to Sum Even Elements

我試圖使用Python解決以下問題:

Fibonacci序列中的每個新術語都是通過添加前兩個術語生成的。 從1和2開始,前10個術語將是:1,2,3,5,8,13,21,34,55,89,......

通過考慮Fibonacci序列中的值不超過四百萬的項,找到偶數項的總和。

到目前為止,我已經能夠生成Fibonacci元素,但在嘗試對偶數元素求和時,我的代碼似乎停滯不前。 以下是代碼:

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)

歡迎大家提出意見。

你有一個無限循環,因為你的while循環中n不會從零增加。 另外,為什么不總和你的Fibonacci總數以及在同一個while循環中找到下一個Fibonacci值,如下所示:

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

輸出:

4613732

因為這看起來像是家庭作業,所以我投入了一些有趣的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)

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

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. 所有Fibonacci數(偶數和奇數)直到並包括Fib(n)的總和是Fib(n+2) - 1 (通過感應的簡單證明)。

因此,如果Fib(n)是要包含在總和中的最后一個偶數,那么你想要的總數就是(Fib(n+2) - 1) / 2

您還可以使用生成器並添加數字

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM