2

Countdown.class を実行すると、次の出力が得られます。

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

飛び立つ!

「Blast Off!」の前の数字。最初の 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

4 に答える 4

11

fastfib()メソッドは を返しますがlong、計算はints で行われます。

整数オーバーフローが発生しています。

s として宣言し、 sa,b,cとして宣言しないようにしてください。さらに大きな数値が必要な場合 ( s の範囲外でもある場合) - を調べて使用することをお勧めします。longintlongBigInteger


編集:コメントで@ExtremeCodersが述べたように、forループ 内のコードには別の問題があります。
for (int i = 0; i <= n; n++)for (int i = 0; i <= n; i++)in

于 2012-12-30T14:35:08.913 に答える
4

他の回答に加えて、

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

する必要があります

for (int i = 0; i <= n; i++) {
//                      ^ that's an i
于 2012-12-30T14:40:00.137 に答える
0

long の代わりに 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;
}

}

于 2014-05-15T16:46:11.690 に答える
0

a、b、c のデータ型を long に変更すると、正常に動作するようになります。数値が int の制限を超えています。

于 2012-12-30T14:36:55.777 に答える