Is there a method that calculates a factorial in Java?

Bare naked factorials are rarely needed in practice. Most often you will need one of the following:

1) divide one factorial by another, or

2) approximated floating-point answer.

In both cases, you'd be better with simple custom solutions.

In case (1), say, if x = 90! / 85!, then you'll calculate the result just as x = 86 * 87 * 88 * 89 * 90, without a need to hold 90! in memory :)

In case (2), google for "Stirling's approximation".


Apache Commons Math has a few factorial methods in the MathUtils class.


public class UsefulMethods {
    public static long factorial(int number) {
        long result = 1;

        for (int factor = 2; factor <= number; factor++) {
            result *= factor;
        }

        return result;
    }
}

Big Numbers version by HoldOffHunger:

public static BigInteger factorial(BigInteger number) {
    BigInteger result = BigInteger.valueOf(1);

    for (long factor = 2; factor <= number.longValue(); factor++) {
        result = result.multiply(BigInteger.valueOf(factor));
    }

    return result;
}

I don't think it would be useful to have a library function for factorial. There is a good deal of research into efficient factorial implementations. Here is a handful of implementations.

Tags:

Java