所以我一点也不擅长(轻描淡写)。我正在试图解决欧拉项目中的问题,我已经被困在2。
Fibonacci序列中的每一个新项都是通过添加前两个项来生成的。从1和2开始,头10个术语将是: 1、2、3、5、8、13、21、34、55、89、 通过考虑Fibonacci序列中值不超过400万的项,找出偶数项的和。
下面是我反复尝试修复的代码:(我认为for循环逻辑有问题。)
public class tesy {
public static void main(String args[]) {
int fib = 0;
int tot = 0;
int total = 0;
for (fib = 0; tot < 4000000; fib++) {
tot = fib + (fib + 1);
if (tot % 2 == 0) {
total = tot + total;
}
}
System.out.println(total);
}
}发布于 2015-08-08 16:23:37
你的逻辑在几个方面是错误的,
tot = fib + (fib + 1); /** This will always be `(2*fib + 1)` and `fib` is getting
incremented by 1 each time. You have no reference to the previous two terms of the
sequence. **/尝试下面的逻辑。
class Fibonacci
{
public static void main (String[] args)
{
int fiboFirst = 1;
int fiboSecond =2;
int fib = 0;
int sum = 0;
while(fiboSecond < 4000000)
{
// This will calculate the current term of the sequence
fib = fiboFirst + fiboSecond;
// Below two lines will update fib[i] and fib[i - 1] terms
// for the next loop iteration.
fiboFirst = fiboSecond; // fib[i]
fiboSecond = fib; // fib[i -1]
if (fib % 2 == 0)
{
sum = sum + fib;
}
}
System.out.println(sum+2);
}
}解释 这里,
fiboFirst等价于Fn,而在Fibonacci序列定义中,fiboSecond等价于FN-1.在每个迭代中,应该替换这两个值,以便在下一个迭代中使用。所以我才有这两条线, fiboFirst = fiboSecond;// fibi fiboSecond = fib;// FIBI-1
HERE是上述程序的执行。
发布于 2015-08-08 16:22:56
您似乎没有遵循用于生成fibonacci序列的实际方程,因此没有(明显的)方法来修复您的代码。
int fibA = 1, fibB = 2, total = 0;
while(fibB <= 4000000) {
// Add to the total, set fibA to fibB and get the next value in the sequence.
if(fibB % 2 == 0) total += fibB;
int temp = fibA;
fibA = fibB;
fibB = fibB + temp;
}上面的代码应该找到小于或等于4000000的所有值的和。
发布于 2015-08-08 19:02:03
这里有一个使用BigInteger的解决方案。请核实结果。
public class Fibonacci{
public static void main(String[] args) {
BigInteger r = fibonacciEvenSum();
System.out.println(r);
}
public static BigInteger fibonacciEvenSum(){
int f = 1;
int s = 2;
int mn4 = 4000000;
BigInteger sum = BigInteger.valueOf(0);
while(s <= mn4){
if(s % 2 == 0){
sum = sum.add(BigInteger.valueOf(s));
}
f = f + s;
s = s + f;
}
return sum;
}
}https://stackoverflow.com/questions/31895897
复制相似问题