Different ways to Calculate Factorial in Java
Write a program to find the factorial of a number is a common interview question for java developers for freshers as well as experienced developers. There are many ways to calculate the factorial of the given numbers. We will see them.
1). Using Apache Commons Math
MathUtils class from Apache Commons Math library contains methods like factorial(int); doubles, factorialDouble(int); or logs, factorialLog(int) to calculate factorials of different data types.
Maven dependency
<dependency >
<groupId >org.apache.commons </groupId >
<artifactId >commons-math3 </artifactId >
<version >3.2 </version >
</dependency >
2). Using Iteration
public static int calculateFactorial (int num )
{
int rem = 1;
for ( int i = 1; i <= num; i++ )
{
rem*=i;
}
return r;
}
3). Using Recursion
public static int factorialRecursive( int num )
{
return num == 1 ? 1 : num * factorialRecursive( num-1 );
}
4). Using Java 8 Streams
public static long factorialStreams( long num )
{
return LongStream.rangeClosed( 1, num )
.reduce(1, ( long a, long b ) -> a * b);
}
the explanation is:
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.
In this article, we have seen Different ways to Calculate Factorial in Java.
0 Comments
Post a Comment