大型数字的 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