Project Euler question 2

The program I'm trying to write is supposed to calculate the sum of the even Fibonacci numbers less than 4 million. My code generates the correct values of the sequence, but the sum outputs 2.

It seems that the nested if statement is only executing on the first iteration of the while loop, am I missing something?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>


using namespace std;

int main() {

	int x1 = 1;
	int x2 = 1;
	int x3 = 0;
	int sum = 0;


	while (x3 < 4000000){
			
		x3 = x1 + x2;
                
                if (2 % x3 == 0){

		     sum = sum + x3;

			}
			
		x1 = x2;
		x2 = x3;
		cout << x3 << endl;
	}

	cout << sum << endl;
        return 0;

}
it should be x3 % 2 not the other way around.

[edit] also x2 should start at 2 not 1.[/edit]
Last edited on
You need to reverse your modulo on line 18

if (x3 % 2 == 0)

otherwise the only time 2 % x3 == 0 would be when x3 is actually 2 hence the sum being equal to 2.

edit..

if he starts with x2 = 2 then he will miss out on the first even fibonacci number in his sum.
Last edited on
Ah I see I was thinking he had lines 18-22 and line 16 switched. I like to start mine with f1 & f2 instead of f0 & f1 it's just a preference I suppose.

Topic archived. No new replies allowed.