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
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.
Factorial of zero 0! is 1. Just remember it.
1. 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;
}
2. 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 );
}
3. 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 paira
andb
– 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 of Very Large Numbers
If we run any of the above examples for numbers > 20; we will get incorrect output due to limitations of long
datatype.
System.out.println(getFactorial(20)); // 2432902008176640000
System.out.println(getFactorial(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 getFactorial(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 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 !!
Leave a Reply