factorial in java stream code example
Example 1: Factorial program in java
public class FactorialRecursion
{
public static void main(String[] args)
{
int factorial = 1;
int number = 6;
factorial = factorialFunction(number);
System.out.println("Factorial of " + number + " is : " + factorial);
}
static int factorialFunction(int num)
{
if(num == 0)
{
return 1;
}
else
{
return(num * factorialFunction(num - 1));
}
}
}
Example 2: factorial method library in java
2.4. Factorial Using Apache Commons Math
Apache Commons Math has a CombinatoricsUtils class with a static factorial method that we can use to calculate the factorial.
To include Apache Commons Math, we'll add the commons-math3 dependency into our pom:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
Let's see an example using the CombinatoricsUtils class:
public long factorialUsingApacheCommons(int n) {
return CombinatoricsUtils.factorial(n);
}