Created
April 21, 2016 03:49
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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