Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't quite get Project Euler problem #2 figured out [closed]

Tags:

c++

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.

like image 922
Andrew Avatar asked Nov 30 '09 06:11

Andrew


People also ask

Why is Project Euler so difficult?

What makes a Project Euler problem? The typical problem on Project Euler usually involves number theory. This usually means searching a large number range for numbers that meet certain criteria. The size of the search space usually makes brute force solutions very time consuming or difficult, but not impossible.

Does Project Euler show solutions?

Projecteuler-solutions provides merely a list of answers -- that is, it does not provide solutions or code for individual problems.

What is the Euler problem?

Euler's three-body problem is to describe the motion of a particle under the influence of two centers that attract the particle with central forces that decrease with distance as an inverse-square law, such as Newtonian gravity or Coulomb's law.


1 Answers

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.

like image 114
Matt Joiner Avatar answered Oct 26 '22 20:10

Matt Joiner