views:

483

answers:

4

I'm trying to learn the basics of C++ by going through some Project Euler problems. I've made it to...#2.

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, ...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

My logic:

0, 1, 1, 2, 3, 5
x  y  z
   x  y  z
      x  y  z
         x  y  z

The above is looping through this:

x + y = z
x = y
y = z

My code:

#include <iostream.h>

using namespace std;

int main()
{
    int x = 0;
    int y = 1;
    int z;
    int sum;

    for(y = 1; y <= 4000000; y++) {

          z = x + y;
          x = y;
          y = z;
            if(y % 2 == 0) {
                 sum += y;
                 }
            }
    cout << sum;
    cin.get();
}

That outputs 4613788 The correct answer, though, is 4613732.

I don't know what's wrong. =/.

+9  A: 

You're using y as both the loop variable, and the second term in the sequence.

What you mean to do is:

int x = 0;
int y = 1;
int z;
int sum = 0;

do {
    z = x + y;
    x = y;
    y = z;
    if (y % 2 == 0) sum += y;
} while (y <= 4000000);

Noting that you should probably initialize sum as well.

Matt Joiner
Indeed, remove y++ and use for(y = 1; y <= 4000000;) or maybe even better while(y <= 4000000)
Marcel J.
Oh, ok. That (and setting `sum = 0`) fixed it. It took me a second to figure out why, but I think I've got it.Thanks to all three of you! :)
Andrew
+4  A: 

You're not initialising sum to zero.

Alex Deem
+3  A: 

For a speed improvement, note that the sequence is Even-Odd-Odd (repeats), Even-Odd-Odd.

You don't need to test each number to know if it is even or odd. Just add every third number.

abelenky
I didn't notice that. Thanks for pointing that out. :)
Andrew
+2  A: 

The for loop code block should be something like

while(y <= 4000000) {
    z = x + y;
    x = y;
    y = z;
    if(y % 2 == 0) {
        sum += y;
    }
}

Basically, you should not increment y.

Vijay Kotari