I’m learning programming with Java. This is my solution to the second problem in Project Euler which seems to give the right answer, however, I’m sure it’s buggy.
The problem is if I change the MAX_TERM_VALUE to 100, I get the answer 188. By calculating the answer by hand, I’m expecting 44. It seems that the program loops one to many times but I can’t work out how to stop it doing this.
Thanks in advance.
public static void main(String[] args) {
int fibA = 0;
int fibB = 1;
int fibC = 0;
int total = 0;
while (fibC < MAX_TERM_VALUE) {
fibC = fibA + fibB;
fibA = fibB;
fibB = fibC;
if (fibC %2 == 0) {
total = total + fibC;
}
}
System.out.println(total);
}
private static final int MAX_TERM_VALUE = 4000000;
The reason for error is that you only check that a number is valid after summing up, thus you also get 134 as it first gets over MAX_TERM_VALUE the next iteration.
Look:
You should do the following instead:
Which should work as the check is done before summing up.