Skip to content

Instantly share code, notes, and snippets.

@SupaHam
Created April 21, 2016 03:49
Show Gist options
  • Save SupaHam/3eec6d2fa89b0344cf7dade29760681b to your computer and use it in GitHub Desktop.
Save SupaHam/3eec6d2fa89b0344cf7dade29760681b to your computer and use it in GitHub Desktop.
Very efficient Fibonacci algorithm that caches previous values to save on calculation times
package com.supaham.test;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class Fibonacci {
private static Map<BigInteger, BigInteger> fibIndex = new HashMap<>();
private static final BigInteger TWO = BigInteger.valueOf(2);
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
System.out.println(i + " " + F(BigInteger.valueOf(i)));
}
System.out.println("Done in " + (System.currentTimeMillis() - start) + "ms.");
}
public static BigInteger F(BigInteger number) {
if (number.equals(BigInteger.ZERO)) {
return BigInteger.ZERO;
} else if (number.equals(BigInteger.ONE)) {
return BigInteger.ONE;
} else {
if (fibIndex.containsKey(number)) {
return fibIndex.get(number);
}
BigInteger l = F(number.subtract(BigInteger.ONE)).add(F(number.subtract(TWO)));
fibIndex.put(number, l);
return l;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment