public class Euler2 {
public static void main(String[] args) {
int Num1 = 0;
int Num2 = 1;
int sum = 0;
do
{
sum = Num1 + Num2;
Num1 = Num2;
Num2 = sum;
if (Num2 % 2 == 0)
sum = sum + Num2;
}
while (Num2 < 4000000);
System.out.println(sum);
}
}Fibonacci序列中的每个新项都是通过添加前两个项来生成的。从1和2开始,头10个术语将是:
1、2、3、5、8、13、21、34、55、89、
通过考虑Fibonacci序列中值不超过400万的项,找出偶数项的和。
我不觉得我写错了,但我得到的答案是5702887,我知道应该是4613732。
发布于 2014-11-09 18:58:34
另一种解决办法是:
while而不是do-whilebits操作而不是%aux):
公共静态空洞主(String[] args ) { int sum =0;int x1 = 1;int x2 = 2;x1 < 4000000 ){ if (x1 & 1) == 0){ // x%2 == 0 sum += x1;} x2=x1+x2;// x2 = sum x1=x2-x1;// x1 = x2 }System.out.println(Sum)的旧值;}发布于 2016-06-07 10:38:58
public void execute() {
int total = 1;
int toBeAdded = 1;
int limit = 4000000;
int totalSum = 0;
int temp = 0;
while (total <= limit) {
if (total % 2 == 0) {
totalSum = totalSum + total;
}
temp = toBeAdded;
toBeAdded = total;
total = toBeAdded + temp;
}
}发布于 2013-09-21 00:51:40
我不知道程序应该做什么,但问题的一部分可能是,您在if语句之前将num2分配给sum值,使if语句的内部等价于sum = sum + sum;
另一方面,将局部变量的名称大写是错误的做法。祝好运!
https://stackoverflow.com/questions/18927767
复制相似问题