Java

Java Program for Factorial

While dealing with mathematical problems in Java, there can be instances where the programmer needs to retrieve an outcome based on the succession of values. For instance, multiplying the succession of values rather than computing each of the values individually. In such scenarios, returning the “factorial” of the number is helpful in many cases for reducing the code complexity.

This article will elaborate on the approaches to computing the “factorial” of a number in Java.

How to Compute the Factorial of a Number in Java?

To calculate the factorial of a number in Java, apply the following approaches:

Algorithm for Calculating the “Factorial” of a Number

First of all, let’s implement an algorithm to find the “factorial” of a number. For instance, if the factorial of the number “5” needs to be computed, the corresponding calculation can be done, as follows:

5 -> 5 * 4 * 3 * 2 * 1 = 120;

 

Approach 1: Computing the Factorial of a Number in Java Using “for” Loop

The “for” loop is used to iterate through the values and display them individually. This approach can be utilized to iterate the loop from “1” to the number(computed for factorial) and return their multiplication.

Example

Go through the following example:

public class factorial {
 public static void main(String args[]){
  int number = 5;
  int factorial = 1;
  for(int i = 1; i <= number; ++i){
   factorial *= i;
}
  System.out.println("The factorial of "+ number +" is: "+factorial);
}}

 
According to the above code snippet, apply the following steps:

    • Firstly, initialize the stated integers.
    • After that, apply a “for” loop to iterate from “1” to the number whose factorial needs to be computed.
    • In the loop definition, return the multiplication of the successive integers starting from “1” till the number.
    • Lastly, display the corresponding factorial of the number.

Output


In this output, it can be analyzed that the factorial of the corresponding number is returned.

Alternative Logic

Alternatively, the factorial can be computed by simply reversing the “for” loop logic in the above example, as follows:

for(int i = number; i >= 1; --i){
 factorial *= i;
}

 
Here, it performs the iteration reversely, i.e., starting from the number(to be calculated for factorial) till “1” and returning the factorial.

Output


As observed, the outcome is identical in this case as well.

Approach 2: Computing the Factorial of a Number in Java Using “while” Loop

The “while” loop is utilized to iterate infinitely. This loop can be applied to, likewise, iterate along the values starting from “1” till the number(computed for factorial) and multiplying them.

Example

The below-provided example explains the stated concept:

public class factorial {
 public static void main(String args[]){
  int number = 5;
  int factorial = 1;
  int x = 1;
  while(x<=number){
   factorial *= x;
   x++;
}
  System.out.println("The factorial of "+ number +" is: "+factorial);
}}

 
In the above lines of code:

    • Similarly, initialize the stated integers.
    • Now, apply the “while” loop to iterate from “1” till the number to be calculated for factorial.
    • In the loop definition, multiply the iterated integers one by one by incrementing them considering the specified condition.

Output


As indicated, this outcome yielded the correct calculation.

Approach 3: Computing the Factorial of a Number in Java Using “Recursion”

Recursion” in Java is a process in which a method calls itself continuously. This approach can be applied by taking a user input number and computing it for factorial by invoking the function repeatedly within the same function.

Firstly, include the below-given package before heading to the example to ensure user input:

import java.util.Scanner;

 
Example

Now, let’s consider the following example:

public class factorialrecursion {
 static int factorial(int n){
  if (n == 0)
   return 1;
  else
   return(n * factorial(n-1));
}
 public static void main(String args[]){
  Scanner obj = new Scanner(System.in);
  System.out.println("Enter the number: ");
  int num = obj.nextInt()
  System.out.println("The factorial becomes: "+factorial(num));
  obj.close();
}}

 
According to this code:

    • Define a function named “factorial()”.
    • The function parameter corresponds to the number to be evaluated for factorial.
    • In its(function) definition, return “1” in case of the number being “0” via the “if” statement.
    • Otherwise, invoke the same function in which it is defined and multiply the passed number with all of its consecutive successors less than it till “1”.
    • In the “main()” method, create a “Scanner” object using the “new” keyword and the “Scanner()” constructor, respectively.
    • The “System.in” parameter reads the input and the “nextInt()” method takes user input as integers.
    • Lastly, invoke the “recursive” function and pass the user input integer as its argument that needs to be calculated for factorial.

Output


 

This output signifies that the desired outcome is retrieved.

Conclusion

To compute the “factorial” of a number in Java, apply the “for” loop, the “while” loop, or the “Recursion” approach. The former two approaches return the factorial by iterating from “1” to the provided integer and multiplying the iterated values. The latter approach computes the factorial such that the function accesses itself repeatedly. This blog computes the factorial of the specified or user input number in Java.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.