Java Programs to Calculate Factorial

We may be asked to write a program to calculate factorial during coding exercises in Java interviews. This always better to have an idea of how to build such a factorial program.

1. What is Factorial?

The factorial of a number is the product of all positive descending integers up to 1. Factorial of n is denoted by 'n!'. For example, we may write the factorial of 5 as:

5! => 5 * 4 * 3 * 2 * 1 => 120

Factorial of zero 0! is 1. Just remember it.

2. Calculate Factorial using Iteration

Simple and the most basic version to find the factorial of a number.

public static long factorialIterative(long n) {

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

3. Calculate Factorial using Recursion

Using plain simple recursion may not be a good idea for its lower performance, but recursion will Tail-Call-Optimization can be a very good implementation for finding the factorial of very large numbers. This is a well-accepted answer as well.

public static long factorialRecursive(long n) {

  return n == 1 ? 1 : n * factorialRecursive(n - 1);
}

4. Calculate Factorial using Stream API

We can use Java Stream API to calculate factorial in the most 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.

5. Calculate Factorial of Very Large Numbers

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

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

The calculated values just get bigger than what long can hold.

The BigInteger class can allocate as much memory as it needs to hold all the bits of data it is asked to hold. Obviously, if that much memory is present in the system, then only.

public static BigInteger getFactorialOfLargeNumber(int num) {

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

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

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

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode