Andrew - 11 months ago 49

C++ Question

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. =/.

Answer Source

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.