Project Euler: Problem 2

Brendan Coady
Oct 21, 2020

Even Fibonacci Numbers

Problem:

Find the sum of even Fibonacci numbers under 4 million.

Approach:

First step is to create a function that produces all the Fibonacci numbers.

I am fortunate to have seen someone else’s brilliant solution to this problem:

a = first number
b = second number
c = a + b
Then make:
a = b
b = c
Repeat as needed.

This is a great solution because it doesn’t store each Fibonacci number, taking up memory, it simply calculates each Fibonacci number from the previous two and overwrites past values.

Step two is two add a criteria to check if the current Fibonacci number is even.

I used modulo division for this, but in hindsight, the better way to do this is to notice that every 3rd number is even. This is because the first 2 are odd:
Odd + Odd = Even
Odd + Even = Odd
Even + Odd = Odd
Then the cycle repeats.

If the number is even, I add it to a rolling sum, and repeat until the value of the Fibonacci number is greater than 4 million.

Challenges:

I actually found this one pretty straight-forward. No real challenges here.

Solution:

Here.

Next Steps:

If I were to expand this, I would use the 3rd number idea outlined above rather than modulo division as it is much faster with large numbers.

--

--

Brendan Coady

Mechanical Designer. Hardware Enthusiast. VFC 2015 Alumni.