Project Euler Problem 2

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

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

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

Solution

To solve this problem, let us see Fibonacci sequence whose values do not exceed 10.

  • The Fibonacci sequence starts with 0 and 1.

  • Add the previous two numbers p and c to get the new Fibonacci number.

  • But our problem is to add only even numbers in the Fibonacci sequence that do not exceed four million, so each time a new Fibonacci number is found, check if the number is even and is not exceeding four million.

Implementation

int MAX_NUM = 4000000;

int main()
{
    int new_f, prev_f, curr_number, sum;
    new_f = 0;
    prev_f = 0;
    curr_number = 1;
    sum = 0;
    while (new_f <= MAX_NUM)
    {
        new_f = curr_number + prev_f;
        if ((new_f <= MAX_NUM) && (new_f % 2) == 0) sum = sum + new_f;
        prev_f = curr_number;
        curr_number = new_f;
    }
    printf("%d", sum);
    return 0;
}

Comments