Today i work on a problem which is:
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.
This is a problem on Project Euler,here is the link:
https://projecteuler.net/problem=2
I Idon't know what's wrong with my code.I think my logic is right,but i still get a wrong answer. I have tested n<100,n<500,n<2000 and i get the right answer,so i think this code would be right when n<4000000.
Here is my code
#include <stdio.h>
long long int Fib(int n){
if (n == 1){
return 1;
}
else if (n == 2){
return 2;
}
else {
return (Fib(n - 1) + Fib(n - 2));
}
}
int main()
{
int i;
long long int sum=0;
for(i=2;Fib(i)<4000000;i=i+2){
sum+= Fib(i);
}
printf("%lld",sum);
return 0;
}
when n<4000000,my answer is 5702886