# Euler Problem 2¶

Back to overview.

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.

In [1]:

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

Test fibonacci sequence generator by comparing the result to the example in the task statement.

In [2]:

    i = fibonacci_generator()
    fib_10 = [next(i) for _ in range(10)]
    assert(fib_10 == [1, 2, 3, 5, 8, 13, 21, 34, 55, 89,])

Greate a function which returns all even-valued fibonacci values smaller or equal to four million.

In [3]:

    def get_even_fibonaccis_smaller_or_equal_four_million():
        r = []
        i = fibonacci_generator()
        current_value = next(i)
        while current_value <= 4000000:
            if current_value % 2 == 0:
                r.append(current_value)
            current_value = next(i)
        return r

Calculate the solution.

In [4]:

    f = get_even_fibonaccis_smaller_or_equal_four_million()
    print(sum(f))

    4613732

I looked at the solutions in the forum and I kind of forgot about simple straight forward approaches. There is no need to create a list and the sum it up. Instead I can simply increment a counter which will be much faster, but less readable maybe.

In [1]:

    r, a, b = 0, 0, 1

    while b <= 4000000:
        if b % 2 == 0:
            r += b
        a, b = b, a + b

    print(r)

    4613732