大型數字的 Fibonacci 數,以 Java 實現
Fibonacci 級數的 Fibonacci 數會呈指數級增長,並且對於 500 或 1000 等大數字來說會非常大。要處理此類數字,long 資料型別是不夠的。BigInteger 可以輕鬆處理大數字。BigInteger 在計算結果超出可用的基本資料型別限制的場景中很有用。請參閱以下示例,以獲取 100 和 1000 的 Fibonacci 數。
示例
import java.math.BigInteger;
public class Tester {
public static void main(String args[]) {
System.out.println("Fibonacci of 100: ");
System.out.println(fibonacci(100));
System.out.println("Fibonacci of 1000: ");
System.out.println(fibonacci(1000));
}
private static BigInteger fibonacci(int n) {
BigInteger a = BigInteger.ZERO;
BigInteger b = BigInteger.ONE;
BigInteger c = BigInteger.ONE;
for (int i=2 ; i<=n ; i++) {
c = a.add(b);
a = b;
b = c;
}
return a;
}
}輸出
Fibonacci of 100: 218922995834555169026 Fibonacci of 1000: 2686381002448535938614672720214292396761660931898695 2340123175997617981700247881689338369654483356564191 8278561614433563129766736422103503246348504103776803 67334151172899169723197082763985615764450078474174626
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP