Tuesday, February 2, 2016

How will you calculate a Large Factorial in Java?

Primitive integer is of 4 bytes signed type in Java, so can hold max value of 2147483647. If any calculation requires to store a larger number than this, Java provides BigInteger class to handle that scenario.
BigInteger can theoretically hold an arbitrary-precision integer value limited by your computer memory. Thus BigInteger is an ideal candidate for calculating factorial of a large number.
BigInteger Documentation
Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two’s-complement notation (like Java’s primitive integer types). BigInteger provides analogues to all of Java’s primitive integer operators, and all relevant methods from java.lang.Math.
Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.
Factorial - basic implementation using primitive integer
static int factorial(int n) {
    int output;
    if (n == 1) {
        return 1;
    output = n * factorial(n - 1);
    return output;

Factorial - using BigInteger
public static BigInteger factorial(BigInteger num) {
    BigInteger factorial = BigInteger.ONE;
    for (BigInteger i = BigInteger.ONE; i.compareTo(num) <= 0; i = i.add(BigInteger.ONE)) {
        factorial = factorial.multiply(i);
    return factorial;

The same program can be written using Java 8 streams, utilizing parallel() streams and reduce() function.
Factorial - Using BigInteger and Java 8 Streams
public static BigInteger factorial(long num) {
    Stream<BigInteger> bigIntStream = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE)).limit(num);
    return bigIntStream
            .reduce((previous, current) -> previous.multiply(current))
            .get(); (1)

  1. This method will utilize all cores of processor by splitting the work using parallel streams, thus performance should be better.

For more such questions, you can get my ebook

1 comment:

  1. This is a good solution. But why aren't you using Streams to solve your problems. They are more concise and efficient than Iterators.


Your comment will be published after review from moderator