BigIntegerFib lol

This commit is contained in:
2023-09-22 16:25:19 -05:00
parent 780c56095f
commit d84b96f688
33 changed files with 3607 additions and 135 deletions

View File

@@ -0,0 +1,47 @@
/*
* 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];
}
}

View File

@@ -0,0 +1,35 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package bigintegerfibonacci;
/**
*
* @author caleb
*/
public class StackSize {
public static void main(String[] args) {
try {
//System.out.println(fact(1 << 15));
System.out.println(infinateRecursion(0));
}
catch (StackOverflowError e) {
System.err.println("true recursion level was " + level);
System.err.println("reported recursion level was " +
e.getStackTrace().length);
}
}
private static int level = 0;
public static long fact(int n) {
level++;
return n < 2 ? n : n * fact(n - 1);
}
public static long infinateRecursion(long n) {
level++;
return infinateRecursion(n++);
}
}