欧拉计划 #2 的输出不正确 - Java

Incorrect Output for Project Euler #2 - Java

我要解决的单词问题:

斐波那契数列中的每一项都是通过添加前两项生成的。从 1 和 2 开始,前 10 项将是:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
考虑斐波那契数列中不超过四百万的项,求偶数项之和

我确定您之前在 Project Euler 上看到过有关此问题的问题,但我不确定为什么我的解决方案不起作用,所以我希望您能提供帮助!

public class Problem2Fibonacci {

public static void main(String[] args) {
    /* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
        1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
        By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */

    int sum = 0; // This is the running sum
    int num1 = 1; // This is the first number to add
    int num2 = 2; // This is the second number
    int even1 = 0;
    int even2 = 0;
    int evensum = 0;

    while (num2 <= 4000000){ // If i check num2 for the 4000000 cap, num will always be lower

        sum = num1 + num2;  // Add the first 2 numbers to get the 3rd

        if(num2 % 2 == 0){ // if num2 is even
            even1 = num2; // make even1 equal to num2
        }
        if(sum % 2 == 0){ // if sum is even
            even2 = sum; // make even2 equal to sum
        }
        if (even1 != 0  && even2 != 0){ // If even1 and even2 both have values 
        evensum = even1 + even2; // add them together to make the current evensum
        even2 = evensum;
        }
        num1 = num2;
        num2 = sum;
        System.out.println("The current sum is: " + sum);
        System.out.println("The current Even sum is: " + evensum);
    }
  }
}                    

所以我的两个问题是, 1. 为什么我的求偶数和的计划不能正常工作? 和 2. 上次我的循环运行时,它使用了 > 4000000 的 num2。为什么?

谢谢!

这应该对您有所帮助:

    int first = 0;
    int second = 1;
    int nextInSeq =first+second;
    int sum =0;

    while(nextInSeq < 4000000) {
        first = second;
        second = nextInSeq;
        nextInSeq = first + second;
        if(nextInSeq % 2 ==0)
            sum = sum + nextInSeq;
        System.out.println("Current Sum = " + sum);
    }
    System.out.println("Sum = " + sum);

对于您的代码片段:even1even2 不是必需的,并且在您继续时它们具有从之前的迭代中保留的价值。