factorial program java code example
Example 1: how to make factorial in java
class fact{
static int fac(int n){
int ans =1;
for(int i=1; i<=n; i++){
ans = ans*i;
}
return ans;
}
public static void main (String[] args){
int f = 5;
System.out.println(fac(f));
}
}
Example 2: factorial program in java
public class FactorialDemo
{
public static void main(String[] args)
{
int number = 6, factorial = 1;
for(int a = 1; a <= number; a++)
{
factorial = factorial * a;
}
System.out.println("Factorial of " + number + " is : " + factorial);
}
}
Example 3: 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);
}