斐波那契数列的斐波那契数呈指数增长,对于500或1000这样的大数来说可能非常大。要处理该数,长数据类型是不够的。BigInteger可以轻松处理大量数字。BigInteger在计算得出的数据超出可用原始数据类型的限制的情况下很有用。请参阅下面的示例,以获取斐波那契数为100和1000。
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