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.
I'm a pretty bad programmer so I'm trying to get better by doing these problems. At first I got an answer of around 2 million but I think that is the wrong answer (i took a peek somewhere online and the answer is around 4.1 million). I edited my code and now I keep on getting 0. I DONT KNOW WHATS WRONG and it's bothering me a lot......... please help!!!
#include <iostream>
usingnamespace std;
int initialfib1;
int initialfib2;
int nextfib = 0;
int fibfunc(int initialfib1,int initialfib2)
{
int n;
//define a function that defines the fibonacci sequence
while(nextfib<4000000)
{
if(nextfib%2 == 0)
{
n = nextfib;
n += n;
}
nextfib = initialfib1 + initialfib2;
initialfib1 = initialfib2;
initialfib2 = nextfib;
fibfunc(initialfib1, initialfib2);
}
return n;
}
int main()
{
int x;
x = fibfunc(0,1);
cout << x;
}
Well, ints can only store values up to positive 2 million ish, so if there are Fibonacci numbers that are above that but below 4 million you'll get an incorrect answer.