Project Euler - 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.

Approach in pseudo-code¶

A Fibonacci sequence can be expressed in mathematical formula as: $F_{n} = F_{n-1} + F_{n-2}$

First, create the Fibonacci sequence with condition meets that the last term do not exceed a pre-defined limit (e.g stated above as 4M).

Then, use a conditional statement to select every even (divisible by 2) terms and add up to the sum container.

-> Then the loop reach to the last iteration, return the sum value.

In [ ]:
# Execution of the above script, for a sequence below 100
n1, n2 = 1, 1
sum = 0
while n2 < 100:
    n1, n2 = n2, n1 + n2
    if n1 % 2 == 0:
        sum += n1
print(sum)
44
In [ ]:
# Put everything into a function, with first parameter indicates the upper limit of the sequence
def Fib_of_even(x):
    n1, n2 = 1, 1
    sum = 0
    while n2 < x:
        n1, n2 = n2, n1 + n2
        if n1 % 2 == 0:
            sum += n1
    return sum

# Execute the function with 4M set as the upper limit of the sequence:
print(Fib_of_even(4 * 10**6))
4613732