Published: April 3, 2023

Project Euler

Problem 2 - Even Fibonacci numbers

Problem

This problem comes from Project Euler 2

Problem

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,...1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solution

If you understand how a Fibonacci sequence works, then the code below is understandable. The solution has been written in both Python and Rust, and either one will work.

# Project Euler: Problem 2
# Even Fibonacci Numbers

fp = 0 # previous fibonacci number
fc = 1 # current fibonacci number
sum = 0

while fc < 4000000:
    fn = fc + fp # fn is the next fibonacci number

    if (fn % 2 == 0):   # if next is divisible by 2
        sum += fn

    fp = fc             # current becomes previous
    fc = fn             # next becomes current

print(sum)
// Project Euler: Problem 2
// Even Fibonacci Numbers
// Alternate Rust version

fn main() {
    let mut f_p = 0;     // Previous Fibonacci number
    let mut f_c = 1;     // Current Fibonacci number
    let mut sum = 0;

    while f_c < 4000000 {
        let f_n = f_c + f_p;   // f_n is the next Fibonacci number

        if f_n % 2 == 0 {
            sum += f_n;
        }

        f_p = f_c;
        f_c = f_n;
    }

    println!("{}", sum);
}