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, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include<iostream>
using namespace std;
long fib;
long long even=0;
long fibonacci(long number)
{
int n1=0;
int n2=1;
for(int i=2;i<number;i++)
{
fib=n1+n2;
n1=n2;
n2=fib;
if(fib%2==0)
{
even+=fib;
}
}
return even;
}
int main()
{
int n;
cout << "enter a number\n"<<endl;
cin >> n;
fib = fibonacci(n);
cout << "fibonacci sum of\t"<<n<<"is\t"<<even;
return 0;
}
|
enter a number
4000000
fibonacci sum of 4000000is 2111290219918
|
It says the output is incorrect. I don't understand what went wrong. Any inputs?
Thanks in advance :) P.S. I don't know the answer.