Select Page

Project Euler 2 Problem Statement

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, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Solution

The Fibonacci sequence is formally defined by the recurrence relation:

F_1=1, F_2=1, F_n=F_{n-1}+F_{n-2}

and generates the sequence: {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, … }.

Every third number is even because adding two odd numbers (1+1) sum to an even number, followed by adding 2 sets of even and odd numbers (1+2 and 2+3) which sum to an odd number. This principle propagates through the series ad infinitum. A good explanation on Fibonacci multiples, such as finding the even ones, is provided in the paper: Fibonacci mod k, by Robert McCann, Univ. of Toronto Bahen Centre.

We solve this problem by defining a new generalized Fibonacci sequence of even Fibonacci numbers starting from zero as: {0, 2, 8, 34, 144, 610, … } to produce only even Fibonacci numbers.

G_0=0, G_1=2, G_n = 4\cdot G_{n-1} + G_{n-2}

This works very well, requiring only 11 iterations for a limit of 4×106 and 27 iterations for 4×1016.

HackerRank version

HackerRank runs 10,000 trials and sums even Fibonacci numbers, N, where 10 ≤ N ≤ 4×1016. This solution easily handles these parameters as well.

Python 2.7 Source

Last Word