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
.
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.
Projecteuler-solutions provides merely a list of answers -- that is, it does not provide solutions or code for individual problems.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With