我想要解决的问题是:
Fibonacci序列中的每个新项都是通过添加前两个项来生成的。从1和2开始,头10个术语将是:
_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._我相信你以前在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.为什么我的偶数和计划不能正确工作?第二,上次我的循环运行时,它使用的是一个大于4000000的num2。为什么?
谢谢!
发布于 2015-12-04 18:34:05
这应该对你有帮助:
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);对于您的代码段:even1和even2并不是必需的,它们承载的值是在您继续进行之前的迭代时保存的。
https://stackoverflow.com/questions/34094875
复制相似问题