Question

I am attempting problems from Project Euler.net. The problem I am stuck on goes like this.

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

I have come up with the following code.

#include<iostream>
#include<cstdlib>
using namespace std;

int main() {
int a=1,b=1,c,sum=0;
    while(c<4000000)
    {
        c=a+b;
        if((c%2)==0)
        sum+=c;

        a=b;
        b=c;
    }
     cout<<sum;
    return 0;
}

The sum returned is always zero. I have looked at the other solutions on StackOverflow but am not able to understand the problem in my solution. Any help appreciated.

Was it helpful?

Solution

You haven't initialized c before entering the loop. If it contains something larger than your limit, the loop won't execute, and sum will remain 0 after the loop terminates.

OTHER TIPS

public class Sample {

public static void main(final String args[]) {


    // fibno me even terms
    int a = 0, b = 1;
    int temp = 0;

    // print fibo below 4 million
    for (int i = 0; i <= 4000000; i++) {

        int c = a + b;

        // System.out.println(c);

        if (c % 2 == 0)

        {

            temp = temp + c;


            // System.out.println("Even" + c);
        }
        a = b;
        b = c;

    }

    System.out.println("temp value is " + temp);

}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top