Skip to content

Instantly share code, notes, and snippets.

@alysbrooks
Created March 24, 2012 05:32
Show Gist options
  • Save alysbrooks/2178629 to your computer and use it in GitHub Desktop.
Save alysbrooks/2178629 to your computer and use it in GitHub Desktop.
Arbitrary precision factorial calculator using recursion
import java.util.Scanner;
import java.math.BigInteger; //For arbitrary precision arithmatic
public class Factorial {
public static BigInteger factorial(String input) {
//BigInteger means the program fails b/c of a stack overflow rather
//than an integer or long overflow. (Happens between 9000! and 10000!)
BigInteger result = new BigInteger(input);
if(result.compareTo(BigInteger.ZERO) > 0) {
return result.multiply(factorial(result.subtract(BigInteger.ONE).toString()));
}
return BigInteger.ONE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment