The factorial calculation pseudo code recursively looks like this:
function factorial(n) { if (n == 0) return 1; else return n * factorial(n - 1); }
Implementing it using BigInteger will be:
public static BigInteger factorial(BigInteger n) { if (n.equals(BigInteger.ZERO)) return BigInteger.ONE; else return n.multiply(factorial(n.subtract(BigInteger.ONE))); } public static void main(String[] args) { System.out.println(factorial(new BigInteger("100"))); }
The output will be:
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000000000
Note : recursion takes up too much memory if n is large. In this case, it is better to use some iterative algorithm to calculate the factorial.
source share