Problem 2
Statement
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, …
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
Solution
The code, in C.
#include <stdio.h>
int fibSum(unsigned int max){
unsigned int a=0;
unsigned int b=2;
unsigned int tmp;
unsigned int t=0;
while(b < max){
tmp=b;
b=4*b+a;
a=tmp;
t+=a;
}
return t;
}
int main(void){
printf("%d\n",fibSum(4000000));
return 0;
}
Answer
4613732
SPEAK / ADD YOUR COMMENT
Comments are moderated.
Posts