Project Euler#2的输出不正确 - Java

时间:2015-12-04 18:18:25

标签: java fibonacci

我试图解决的问题:

Fibonacci序列中的每个新术语都是通过添加前两个术语生成的。从1和2开始,前10个术语将是:
            1,2,3,5,8,13,21,34,55,89,......             通过考虑Fibonacci序列中的值不超过四百万的项,找到偶数项的总和。

我确定您以前在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.我的循环最后一次运行时,它使用的num2是&gt; 4000000.为什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

这可以帮到你:

    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不是必需的,并且在您继续操作时它们具有从之前的迭代中保留的值。