Jorge Martinez

Aerospace Engineer and Senior Software Developer


Project Euler: solution to problem 002

Jorge Martínez Garrido

March 15, 2023

programming c rust python


Mathematical background

The Fibonaci sequence is defined as:

$$ \phi_{n} = \phi_{n-1} + \phi_{n-2} $$

where $\phi_{0} = 0$ and $\phi_{1} = 1$.

A number is even if the remainder of its Euclidean division by two is zero.

Therefore, we only need to sum the even terms of the Fibonacci sequence whose values do not exceed four million.

Implementing the Fibonacci sequence

There are two ways to implement the Fibonacci sequence: using recursive functions or using a loop. The recursive approach is very readable while not performant. The loop approach may be less readable but avoids computing various times the same terms of the series.

Trying to generate a Fibonacci function is not the best from the performance point of view, not matter if it uses a loop or recursion. The issue is that we need to check for an UPPER_BOUND, in this case $4000000$. However, we have no idea for which $n$ this bound is achieved. Hence, it is better to keep computing sequence values.

Solution

Output

Answer: 4613732