偶数Fibonacci项的总和是错误的

时间:2011-06-05 15:07:18

标签: java

我正在学习Java编程。这是我对the second problem in Project Euler的解决方案,似乎给出了正确的答案,但是,我确定它是错误的。

问题是如果我将MAX_TERM_VALUE更改为100,我得到答案188.通过手动计算答案,我期待44。似乎程序循环一次到多次但我无法解决如何阻止它这样做。

提前致谢。

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;

2 个答案:

答案 0 :(得分:1)

错误的原因是你只能在总结之后检查一个数字是否有效,因此在下一次迭代中它首次超过MAX_TERM_VALUE时也会得到134.

查找

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;  

您应该执行以下操作:

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;  

在总结之前检查完成后哪个应该有效。

答案 1 :(得分:0)

手动计算答案后,尝试在调试器中运行程序,逐步执行100限制的每个语句,观察变量。你最终会看到它总共增加144,希望能够找出原因。