3 Ways to Calculate Factorial in Java

Writing a program to calculate factorial in java – can be a coding exercise during java interviews. It’s always better to have idea of how to build such factorial program. Let’s go through such three ways:

1) Calculate Factorial Using Iteration

Simple and most basic version. Good to know but not right to use for performance reason.

public static long factorialIterative ( long n ) 
{
	long r = 1;
    for ( long i = 1; i <= n; i++ ) 
    {
        r*=i;
    }
    return r;
}

2) Calculate Factorial Using Recursion

If you are working on java 7 or lower version, then it is your best option. A well accepted answer as well. It uses recursion to calculate factorial.

public static long factorialRecursive( long n ) 
{
    return n == 1 ? 1 : n * factorialRecursive( n-1 );
}

3) Calculate Factorial Using Streams [Java 8]

Java 8 has support for streams which you can use to calculate factorial in mlst effective manner as below.

public static long factorialStreams( long n )
{
    return LongStream.rangeClosed( 1, n )
                     .reduce(1, ( long a, long b ) -> a * b);
}
  • Here, LongStream.rangeClosed(2, n) method creates a Stream of longs with the content [2, 3, ... , n].
  • reduce (a, b) -> a * b means that each pair a and b – multiply them and return the result. The result then carries over to a for the next round.
  • The value “1” used in the reduced method is used as a starting value for variable a for the very first iteration.

4) Calculate Factorial for Numbers Greater than 20 using BigInteger

If you run any of above examples for numbers > 20; you will get incorrect output due to limitations of long datatype.

System.out.println(getFactorial(20)); // 2432902008176640000
System.out.println(getFactorial(21)); // -4249290049419214848

Values just get bigger than what long can hold. The BigInteger class allocates as much memory as it needs to hold all the bits of data it is asked to hold. Obviously if that much memory is preset in system, then only.

Now you will need BigInteger to hold more bigger values and use below code to get factorial.

public static BigInteger getFactorial(int num) {
    BigInteger result = BigInteger.ONE;
    for (int i = 1; i <= num; i++)
        result = result.multiply(BigInteger.valueOf(i));
    return result;
}

Now you can get factorial of any number no matter how large it is.

System.out.println(getFactorial(22)); // 1124000727777607680000
System.out.println(getFactorial(32)); // 263130836933693530167218012160000000
System.out.println(getFactorial(132)); // Indeed a very long number is printed - Try yourself.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “3 Ways to Calculate Factorial in Java”

  1. Why should the perfomance of the first method be better than the second one? It follows the dynamic programming method, one calculates the partial results with the space of one variable and the iteration variable. Yes each time the <-Test has to be resolved, but thats much "cheaper" than to initiate the function/method each time, create the new parameterset on the stack and generating more memory until the last factorial is resolved.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.