Paul Waring

Freelance C Developer based in Manchester, UK

Project Euler problem 2

Even Fibonacci Numbers

Find the sum of the even Fibonacci numbers up to 4 million.

Solution

Calculating the Fibonacci numbers is straightforward and requires minimal memory, as we only have to keep track of the current number and the previous two numbers. Checking if a number is even is as simple as dividing by 2 and looking for a remainder of 0.

#include <stdlib.h>
#include <stdio.h>

int main() {
    int sequence[] = {1, 1, 2};
    int sum = 0;

    while (sequence[2] < 4000000) {
        // Check if current number is even
        if (sequence[2] % 2 == 0) {
            sum += sequence[2];
        }

        // Move all numbers back one space,
        // then recalculate current number
        sequence[0] = sequence[1];
        sequence[1] = sequence[2];
        sequence[2] = sequence[0] + sequence[1];
    }

    printf("%d\n", sum);

    return EXIT_SUCCESS;
}
    

An alternative method, to remove the modulus operation, would be to check if the last digit is 0, 2, 4, 6 or 8. However, division by 2 is usually something that a compiler can optimise to something other than a DIV instruction.