简体   繁体   中英

Using Fibonacci Program to Sum Even Elements

I am trying to solve the following using Python:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

So far, I have been able to generate the Fibonacci elements but in trying to sum the even elements, my code seems to stall. Here is the code below:

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)

Any suggestions would be welcome.

You have an infinite loop as n isn't ever incremented up from zero in your while loop. Additionally, why not sum your Fibonacci total as well as find the next Fibonacci value in the same while loop, like this:

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

Outputs:

4613732

since this looks like a homework assignment, I threw in some interesting 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)

Just for fun, here's a really short solution:

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

It's based on the following facts:

  1. Every third Fibonacci number is even.

  2. If Fib(n) is even, then the sum of the even Fibonacci numbers up to Fib(n) is equal to the sum of the odd Fibonacci numbers up to Fib(n) (because each even Fibonacci number is the sum of the two preceding odd Fibonacci numbers).

  3. The sum of all Fibonacci numbers (even and odd) up to and including Fib(n) is Fib(n+2) - 1 (via an easy proof by induction).

So if Fib(n) is the last even number to be included in the sum, then the total you want is just (Fib(n+2) - 1) / 2 .

You can also use a generator and add the numbers

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM