Skip to content

Instantly share code, notes, and snippets.

@sheradmin
Created September 9, 2019 20:25
Show Gist options
  • Select an option

  • Save sheradmin/01c7d03084cf848a7626c9bd32e6a261 to your computer and use it in GitHub Desktop.

Select an option

Save sheradmin/01c7d03084cf848a7626c9bd32e6a261 to your computer and use it in GitHub Desktop.
import java.math.BigInteger;
public class Fibonacci {
private int fib1(int n) {
if (n == 1 || n == 2) {
return 1;
}
int r = fib1(n - 1) + fib1(n - 2);
return r;
}
private BigInteger fib2(int n, BigInteger[] memo) {
if (memo == null) {
memo = new BigInteger[n + 1];
}
if (memo[n] != null) {
return memo[n];
}
if (n == 1 || n == 2) {
return BigInteger.ONE;
}
BigInteger r = fib2(n - 1, memo).add(fib2(n - 2, memo));
memo[n] = r;
return r;
}
private BigInteger fibBottomUp(int n) {
if (n == 1 || n == 2) {
return BigInteger.ONE;
}
BigInteger[] memo = new BigInteger[n + 1];
memo[1] = BigInteger.ONE;
memo[2] = BigInteger.ONE;
for (int i = 3; i <= n; i++) {
memo[i] = memo[i - 1].add(memo[i - 2]);
}
return memo[n];
}
public static void main(String[] args) {
Fibonacci fibonacci = new Fibonacci();
//Recursion solution
System.out.println(fibonacci.fib1(15));//after 50 fail
//Store solution
System.out.println(fibonacci.fib2(9200, null));//fail StackOverflowError after 9255
//Bottom up solution
System.out.println(fibonacci.fibBottomUp(200000));//fail Java heap space after 250000
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment