Project Euler Solution 2
#
Problem StatementBy 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.
#
SolutionTo solve this problem, let us see Fibonacci sequence whose values do not exceed 10.
note
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.
Finding Fibonacci values whose values do not exceed 10.
note
p and c represents previous and current terms in the Fibonacci sequence
p = 0 | c = 1 |
0 + 1 = 1
0 | p = 1 | c = 1 |
1 + 1 = 2
0 | 1 | p = 1 | c = 2 |
1 + 2 = 3
0 | 1 | 1 | p = 2 | c = 3 |
2 + 3 = 5
0 | 1 | 1 | 2 | p = 3 | c = 5 |
3 + 5 = 8
0 | 1 | 1 | 2 | 3 | p = 5 | c = 8 |
5 + 8 = 13 exceeds 10
In this case 2 and 8 are even, so the sum of even valued terms in the Fibonacci sequence that do not exceed 10 is 2 + 8 = 10.
#
Implementation#include <stdio.h>
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;}