Finding the factorial of a number is an everyday task that we often perform while working with mathematics. It has several real-world implementations, such as determining the ways a deck of cards can be shuffled, finding possible scenarios to arrange the letters of a word without repeating them, and so on. It is denoted by the “!” sign and is defined as “the product of all the positive numbers/ integers less than or equal to the input number”. For instance, the factorial of four (4!) is “24” which is calculated as follows: 4*3*2*1 = 24.
This write-up explains the recursive approach of finding the factorial of any given number in Java.
How to Find Factorial of a Number in Java Using Recursion
Java supports several approaches for finding the factorial of any given number/integer. However, recursion is the most convenient and efficient of all the possible methods. Don’t know what recursion is? No worries! We’re here to resolve your queries. Well! recursion is a process in which a function calls itself until it finds a termination/base condition, as shown below:
To find the factorial of a number in Java using recursion, create a recursive function that takes a number and multiplies it with its preceding numbers recursively until the base condition is fulfilled. You can use different types of recursion (like head, tail, indirect, etc.) to calculate/find the factorial of a numeric value. Let’s implement this concept in Java to find the factorial of any user-entered integer.
Example 1: Find Factorial in Java Using Head Recursion
In Java, head recursion is a type of direct recursion in which the recursive call is made at the start/head of the function (before any other operations). In this example, we use head recursion to compute the factorial of a user-inserted value. We use the Scanner class to get an integer from the user (whose factorial needs to be computed):
package exp;
import java.util.Scanner;
public class FactorialRecursionJava {
public static int findFactorial(int inputNumber) {
if (inputNumber <= 1) {
return 1;
} else {
int computeFact = inputNumber * findFactorial(inputNumber - 1);
return computeFact;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Input a Number For Factorial Calculation: ");
int enterNum = scan.nextInt();
int result = findFactorial(enterNum);
System.out.println("The Factorial of " + enterNum + " = " + result);
scan.close();
}
}
In this code,
- We create a function named “findFactorial()” at the class level. It accepts an integer and returns its factorial.
- Within the function, we use the if-else statement. The if statement contains a base condition that stops the function from calling itself when the input number is/becomes less than or equal to 1.
- The else block contains the code to find the factorial of the input number if it is greater than 1.
- In the main() method, we use the Scanner class to take an integer from the user and pass this number to the findFactorial() function as an argument.
- Finally, we print the factorial of the given integer on the console using the println() method:
Example 2: Find Factorial in Java Using Tail Recursion
Tail recursion is a type of direct recursion in which the recursive call is the last operation performed by the recursive method. Therefore, the result of the recursive call is used/executed directly with the method’s return statement. In the below code snippet, we use the tail recursion to find the factorial of the user-entered number:
package exp;
import java.util.Scanner;
public class FactorialRecursionJava {
static int findFactorial(int num, int baseCase) {
if (num <= 0) {
return baseCase;
}
return findFactorial(num - 1, num * baseCase);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Input a Number For Factorial Calculation: ");
int enterNum = scan.nextInt();
int result = findFactorial(enterNum, 1);
System.out.println("The Factorial of " + enterNum + " = " + result);
scan.close();
}
}
The user entered the number “4”, as a result, we got the following output:
How to Find Factorial of a Number in Java Using Indirect Recursion
The error debugging process of direct recursion is a bit tricky and difficult. To avoid such cases, you can use indirect recursion. Indirect recursion in Java refers to a process in which a method calls/invokes another method and that method calls the first method again. This procedure continues until a function fulfills a base/termination condition. You can use this method to compute the factorial of any given number:
import java.util.*;
public class FactorialRecursionJava {
//This method indirectly calls the computeFactorial()
public static int findFactorial(int num) {
if (num == 0) {
return 1;
} else {
return num * computeFactorial(num - 1);
}
}
//This method indirectly calls the findFactorial()
public static int computeFactorial(int num) {
if (num == 0) {
return 1;
} else {
return num * findFactorial(num - 1);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Input a Number For Factorial Calculation: ");
int enterNum = scan.nextInt();
int result = findFactorial(enterNum);
System.out.println("The Factorial of " + enterNum + " = " + result);
scan.close();
}
}
In the above code,
- We create two functions: “findFactorial()” and “computeFactorial()”.
- Both of them call each other and this recursive behavior continues until the base condition is met (i.e., “num == 0” in this case).
When we execute the above code, it prompts us to enter a number for factorial calculation. We entered “6”, as a result, the factorial of the user-entered value is retrieved as follows:
That’s all about finding factorial in Java using recursion.
Conclusion
To find/calculate the factorial of a number in Java using recursion, create a recursive function that takes a number whose factorial you want to find. This number gets multiplied by its preceding numbers until it meets the base condition (i.e., if (num <= 1) return 1). You can also implement indirect recursion to avoid error debugging difficulties that you may face while finding factorial using direct recursion. This write-up has presented examples to explain how you can find the factorial of a number in Java using recursion.