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

*, 13, 21,*

**8***, 55, 89,*

**34***, 233, 377,*

**144***, … }.*

**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×10^{6} and 27 iterations for 4×10^{16}.

#### HackerRank version

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

#### Python 2.7 Source

#### Last Word

- See Project Euler Problem 104 for more uses of Generalized Fibonacci sequences
- Reference: The On-Line Encyclopedia of Integer Sequences (OEIS) A000045: Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.

## Recent Comments