Java Factorial Program
Factorial of number is the product of all numbers before it including the number itself, till 1. Factorial of 0 is 1.
In this article, we will learn many different ways to calculate factorial of a number with java program.
Execute a loop starting from the number till 1.
Declare a variable to hold the factorial of this number. Initialize it to 1.
In every loop iteration,
A. multiply this variable with the number and store the result back to the variable.
B. Decrease the number by 1.
Thus, when the loop completes, the result variable will contain the product of number with all other numbers before it till 1, hence the factorial.
int num = 5; int fact = 1; while (num >= 1) { fact *= num; num--; }
Method 2: Using for loop
Factorial of a number in java can also be calculated using a for
loop.
In the last example, replace the while loop with a for loop, that runs from 1 till the number. Example,
int num = 5; int fact = 1; for(int i = 1; i <= num; i++) { fact *= i; }
for loop will execute in forward direction from 1 till the number as opposed to while loop, which executed in reverse direction; from the number till 1.
Using a loop to execute repeated statements is called iterative approach.
Same result can be achieved using recursive approach. A recursive method invokes itself again and again.
Thus, instead of using a loop, we call the recursive method repeatedly and supply the number as argument.
Return value from this method is the product of the argument with another call to this method, with the argument decreased by 1. Example,
int factorial(int num) { // check if the argument is 1 if (num == 1) { return 1; } // invoke method again return num * factorial(num - 1); }
Recursive method will keep on calling itself till the argument becomes 1.
In every call, it will return the product of argument and a value which is 1 lesser than the argument.
Do not forget to check for argument equal to 1, else the recursive method will be stuck in an infinite loop, resulting in StackOverflowError.
Method 4: Using Java 8 streams
Java 8 streams can be used to calculate factorial of a number.
java.util.stream.IntStream
class has a rangeClosed()
method, which generates a stream of integers between a range. So, to calculate factorial of 5, we need to generate a stream of integers from 1 to 5.
Applying product operation on these integers using reduce()
method will calculate factorial of 5. Example,
// this will always be 1 int start = 1; // number whose factorial needs to be calculated int number = 5; int factorial = IntStream.rangeClosed(start, number) .reduce((int x, int y) -> x * y) .getAsInt();
reduce()
method takes an object of type IntBinaryOperator
as argument.
This is a functional interface having a single method applyAsInt()
which takes two integer arguments and returns an integer.
So, we can supply a Lambda expression to reduce()
which takes two integer arguments and returns their product.
reduce()
will be invoked for integers from 1 to 5 and return their product, which will be the factorial of 5.
For larger numbers, use LongStream
instead of IntStream
.
For calculating factorial of larger numbers, use
java.math.BigInteger
class, which can store values upto 2^Integer.MAX_VALUE.
BigInteger is analogous to java’s primitive int
value with support for larger values. Since it is a class, we can call methods on this object.
Use a loop to calculate factorial using BigInteger
.
To perform multiplication, use its multiply()
method, which accepts a BigInteger
argument and multiplies the argument value with the value on which multiply()
is invoked. Example,
// result variable initialized to 1 BigInteger factorial = BigInteger.ONE; // calcualte factorial of 60 int num = 60; // loop from 60 to 1 while(num >= 1) { // multiply values factorial = factorial.multiply(BigInteger.valueOf(num)); // decrease the number num--; }
If you want the result as an int
value, use intValue()
method of BigInteger
.
This method works the same as Method 1 and 2, except that we are using BigInteger
in place of primitive int
.
Method 6: Using Guava
Guava library has a class com.google.common.math.BigIntegerMath having method factorial(). This method accepts an integer value and returns its factorial. Example,
int number = 10; BigInteger factorial = BigIntegerMath.factorial(number)
This method can be used to calculate factorial of larger values, since it returns the result as a BigInteger.
factorial()
throws an IllegalArgumentException
if the argument is negative.
To include Guava in your project, add below dependency as per the build tool
Gradle
implementation group: 'com.google.guava', name: 'guava', version: '30.1.1-jre'
Maven
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>30.1.1-jre</version> </dependency>
Method 7: Using Apache Commons Math
Apache Commons Math library has org.commons.math3.util.CombinatoricsUtils
class. This class has factorial()
method which accepts an integer argument and returns its factorial as shown below
int number = 10; long factorial = CombinatoricsUtils.factorial(number);
Note that returned value is of type long
.
This class also has a method factorialDouble()
which returns the factorial as a double
value.
Add Apache Commons Math to your project using the below dependency.
Gradle
implementation group: 'org.apache.commons', name: 'commons-math3', version: '3.6.1'
Maven
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-math3</artifactId> <version>3.6.1</version> </dependency>
That is all on different methods to calculate factorial of a number with java programs.
In all these methods, we used a fixed number but you may also take the number whose factorial needs to be calculated as user input from keyboard.
Simplest of these methods is using nextInt()
method of Scanner class.
Scanner scanner = new Scanner(System.in); System.out.println("Enter a number"); int number = scanner.nextInt(); int fact = 1; while (number >= 1) { fact *= number; number--; }
Do not forget to click the clap.