计算用Java实现的Fibonacci序列的算法给出了奇怪的结果

时间:2012-12-30 14:32:17

标签: java recursion iteration fibonacci

当我运行Countdown.class时,我得到以下输出:

263845041
-1236909152
-973064111
2084994033
1111929922
-1098043341
13886581
-1084156760
-1070270179
2140540357

爆炸!

“爆炸之前”的数字!应该是前10个斐波那契数字。我的源代码如下。

    public class Fibonacci {

  public static long fib(int n) {
    if (n <= 1) return 1;
    return fib(n-1) + fib(n-2);
  }

  public static long fastfib(int n) {
    int a = 0;
    int b = 1;
    int c = 0;

    for (int i = 0; i <= n; n++) {
      c = a + b;
      a = b;
      b = c;    
    }

    return c;
  }

}

,实现fastfib方法的类是:

public class Countdown {

  public static void countdown(int n) {
    if (n == 0) System.out.println("Blast Off!");
    else {
      System.out.println(Fibonacci.fastfib(n));
      countdown(n - 1); 
    }
  }

  public static void main(String[] args) {
    countdown(10);
  }
}

4 个答案:

答案 0 :(得分:12)

虽然您的fastfib()方法返回long,但计算是在int s上完成的。

您遇到integer overflow

请务必将a,b,c声明为long,而不是int。如果你想要更大的数字(也超出long的范围) - 你可能想查看BigInteger(并使用它)。


编辑:正如评论中 @ExtremeCoders 所述,您的for循环中的代码还有另一个问题:
for (int i = 0; i <= n; n++)应为for (int i = 0; i <= n; i++),您希望增加i - 而不是n

答案 1 :(得分:4)

除了其他答案,

for (int i = 0; i <= n; n++) {

应该是

for (int i = 0; i <= n; i++) {
//                      ^ that's an i

答案 2 :(得分:0)

将a,b和c的数据类型更改为long,它将开始正常工作。你的数字超过了int的限制。

答案 3 :(得分:0)

你应该使用BigInteger长期

import java.math.BigInteger;

公共类斐波那契{

public static BigInteger fib(BigInteger n) {
    int result = n.compareTo(BigInteger.valueOf(1)); // returns -1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.
    if (result != 1) return BigInteger.valueOf(1);

    return fib(

            n.subtract(
                    BigInteger.valueOf(1).add
                        (n.subtract
                                (
                                        BigInteger.valueOf(-2)
                                )
                        )
                    )
                );
}

public static BigInteger fastfib(int n) {
    BigInteger a = BigInteger.valueOf(0);
    BigInteger b =  BigInteger.valueOf(1);
    BigInteger c =  BigInteger.valueOf(0);

    for (int i = 1; i < n; i++) {
        c = a.add(b);
        a = b;
        b = c;    
    }

    return c;
}

}