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: 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 previous odd numbers (ex., 1+1) sum to an even number. Then, followed by adding 2 sets of even/odd numbers (ex., 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 for even Fibonacci numbers starting from zero as: {0, 2, 8, 34, 144, 610, … }. This works very well, requiring only 11 iterations for a limit of 4×106 and 27 iterations for 4×1016.

#### HackerRank version

HackerRank requires us to run 10,000 test cases and sum even Fibonacci numbers under a limit, N, where 10 ≤ N ≤ 4×1016. This solution easily handles these parameters without change.