So, I’m new to C++ and I’ve decided to do some Euler problems… The thing is, I can’t seem to get past problem 2. There doesn’t seem to be anything wrong with the logic as far as I can tell, so maybe it’s a programming problem. The build runs, but gives me a wrong answer of 19,544,084.
#include "stdafx.h"
#include <iostream>
using namespace std;
int a = 1;
int b = 2;
int c = 0;
int total = 0;
int _tmain(int argc, _TCHAR* argv[])
{
while (a <= 4000000 || b <= 4000000 || c <= 4000000) {
c = a + b;
if (c % 2 == 0) {
total += c;
}
a = c + b;
if (a % 2 == 0) {
total += a;
}
b = a + c;
if (b % 2 == 0) {
total += b;
}
}
total += 2; // Didn't start with 2 in Fibonacci, so added it at end.
cout << total;
return 0;
}
Your logic is wrong. It is possible that when you enter your loop a, b, and c are all less than 4 million, but the sum of two numbers less than 4 million doesn’t have to be less than 4 million too. Before you add you number to total, you also need to check that the value is less than 4 million.
if (c < 4000000 && c % 2 == 0)Do the same for a and b.