首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >项目Euler #2 - Java的错误输出

项目Euler #2 - Java的错误输出
EN

Stack Overflow用户
提问于 2015-12-04 18:18:25
回答 1查看 109关注 0票数 0

我想要解决的问题是:

Fibonacci序列中的每个新项都是通过添加前两个项来生成的。从1和2开始,头10个术语将是:

代码语言:javascript
复制
         _1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ..._
代码语言:javascript
复制
         _By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms._

我相信你以前在Euler项目上见过关于这个问题的问题,但我不知道为什么我的解决方案不起作用,所以我希望你能帮上忙!

代码语言:javascript
复制
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.为什么我的偶数和计划不能正确工作?第二,上次我的循环运行时,它使用的是一个大于4000000的num2。为什么?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-04 18:34:05

这应该对你有帮助:

代码语言:javascript
复制
    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并不是必需的,它们承载的值是在您继续进行之前的迭代时保存的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34094875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档