Problem 2

Even Fibonacci numbers

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.

Solution

First a generator for the fibonacci (even numbers) is created


In [10]:
#--Fibonnacci number generator (only even numbers)
def fib_gen():
    yield 2
    n = 2
    n_old = 1
    n_new = n + n_old
    while (n_new <= 4000000):
        if (n_new % 2 == 0):
            yield n_new
        n_old = n;
        n = n_new
        n_new = n + n_old

Then, a list with all the even fibbonnacci numbers that not exceed 4000000 is created


In [11]:
l = [f for f in fib_gen()]

Finally, all the elements of the list are summed up


In [12]:
sum = 0
for e in l:
    sum += e
    
print("The solution is: {}".format(sum))


The solution is: 4613732

The list is very short


In [15]:
l


Out[15]:
[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]