Skip to content

Instantly share code, notes, and snippets.

@seangenabe
Created August 14, 2014 21:31
Show Gist options
  • Save seangenabe/419448e0cbe284f6ff8e to your computer and use it in GitHub Desktop.
Save seangenabe/419448e0cbe284f6ff8e to your computer and use it in GitHub Desktop.
import java.util.*;
public class FactorialSolver
{
private static HashMap<Integer, Integer> factorials;
public static int factorial(int n) throws Exception {
if (factorials == null) {
factorials = new HashMap<Integer, Integer>();
factorials.put(0, 1);
}
if (n < 0) {
throw new Exception();
}
if (factorials.containsKey(n)) {
return factorials.get(n);
}
else {
int res = factorial(n - 1) * n;
factorials.put(n, res);
return res;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment