Starting from 1 and 2, compute the sum of all even fibonacci numbers (while these numbers are smaller or equal to 4 million)
I am trying to sum all even fibonacci numbers up to 4e6, but it doesn’t give me anywhere the right result, and I don’t understand where I’ve messed up. In my mind, the conditions for the if are correct.
My fibonacci() function, and my function to sum the even numbers up, is below.
int fibonacci(int k) //compute the k-th fibonacci number (with EulerProject formula)
{
if (k == 1 || k == 2)
{
return k;
}
{
return (fibonacci(k-1)+ fibonacci(k-2));
}
}
int evenfibonacci()
{
int result = 0;
for (int k = 1; fibonacci(k)<=4e6;) {
if (fibonacci(k)%2 == 0 ) {
result += fibonacci(k);
k++;
} else {
k++;
}
}
}
>Solution :
evenfibonacci() is declared as returning an int value, but does not actually return anything, so the return value is alway indeterminate. You need to add a return statement:
int evenfibonacci()
{
int result = 0;
for (int k = 1; fibonacci(k) <= 4e6; ++k) {
if (fibonacci(k) % 2 == 0) {
result += fibonacci(k);
}
}
return result; // <-- ADD THIS
}