开发者

Sum of even-numbered Fibonacci terms is wrong

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 th开发者_Python百科e 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:

public static void main(String[] args) {
    int fibA = 0;
    int fibB = 1;
    int fibC = 0;
    int total = 0;

    while (fibC < MAX_TERM_VALUE) { //fibC is 89 and under MAX_TERM_VALUE = 100
        fibC = fibA + fibB; //fibC is 144 and more than MAX_TERM_VALUE 
        fibA = fibB;
        fibB = fibC;

        if (fibC %2 == 0) {
            total = total + fibC; //The fibC is added anyway as the check only happens next iteration
        }
    } 
    System.out.println(total);  
}
private static final int MAX_TERM_VALUE = 4000000;  

You should do the following instead:

public static void main(String[] args) {
    int fibA = 0;
    int fibB = 1;
    int fibC = 0;
    int total = 0;

    while (true) { 
        fibC = fibA + fibB;  
        fibA = fibB;
        fibB = fibC;
        if (fibC >= MAX_TERM_VALUE){
             break;
        }
        if (fibC %2 == 0) {
            total = total + fibC; 
        }
    } 
    System.out.println(total);  
}

private static final int MAX_TERM_VALUE = 4000000;  

Which should work as the check is done before summing up.


After calculating the answer by hand try running your program in a debugger and stepping through every statement for the 100 limit, watching the variables. You'll eventually see it add 144 to total and hopefully be able to figure out why.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜