Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are my if-conditions correct to sum up the even fibonacci numbers up to 4 million?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading