BigInteger factorial - Java java.math

Java examples for java.math:BigInteger

Description

BigInteger factorial

Demo Code


import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Arraycopy;
import java.util.Random;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;

public class Main{
    public static void main(String[] argv) throws Exception{
        int n = 2;
        System.out.println(factorial(n));
    }//from ww w  .  ja  v  a2 s  .  co  m
    public static BigInteger factorial(int n) {
        return factorial(BigInteger.valueOf(n));
    }
    public static BigInteger factorial(BigInteger n) {
        if (n.equals(ZERO))
            return ONE;

        BigInteger i = n.subtract(ONE);
        while (i.compareTo(ZERO) > 0) {
            n = n.multiply(i);
            i = i.subtract(ONE);
        }
        return n;
    }
}

Related Tutorials