48 lines
1.3 KiB
Java
48 lines
1.3 KiB
Java
/*
|
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
|
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
|
|
*/
|
|
package bigintegerfibonacci;
|
|
|
|
import java.math.BigInteger;
|
|
|
|
/**
|
|
*
|
|
* @author caleb
|
|
*/
|
|
public class BigIntegerFibonacci {
|
|
|
|
/**
|
|
* @param args the command line arguments
|
|
*/
|
|
private static BigInteger[] fibonacciCache;
|
|
public static void main(String[] args) {
|
|
int n = 100000;
|
|
fibonacciCache = new BigInteger[n + 1];
|
|
System.out.println("Calculating fibonacci for number " + n + "...");
|
|
// Precache value to prevent stack overflow
|
|
for (int i = 0; i <= n; ++i) {
|
|
fibonacci(i);
|
|
}
|
|
System.out.println(fibonacci(n));
|
|
|
|
}
|
|
|
|
private static BigInteger fibonacci(int n) {
|
|
// Base case
|
|
int compareInt = BigInteger.valueOf(n).compareTo(BigInteger.ONE);
|
|
//System.out.println("value is: " + compareInt);
|
|
|
|
if (compareInt == -1 || compareInt == 0){
|
|
return BigInteger.valueOf(n);
|
|
}
|
|
if (fibonacciCache[n] != null) {
|
|
return fibonacciCache[n];
|
|
}
|
|
BigInteger nthFibNumber = (fibonacci(n - 1).add(fibonacci(n - 2)));
|
|
fibonacciCache[n] = nthFibNumber;
|
|
return fibonacciCache[n];
|
|
}
|
|
|
|
}
|