Problem Statement:
Create a Java program to find the factorial of a given number using recursion. Factorial is a fundamental concept in mathematics where the factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!.
Input:
An integer n, where n is a non-negative integer.
Example:
Input: 5
Output: 120
Step-by-Step Solution:
Step 1: Understand Recursion
- Recursion is a technique where a method calls itself to solve smaller instances of the same problem. To compute the factorial of a number
n, the problem can be broken down into finding the factorial ofn-1and then multiplying it byn.
Step 2: Base Case
- The base case is crucial for terminating the recursion. For factorial, the base case is when
nis 0 or 1. The factorial of 0 and 1 is 1.
if (n == 0 || n == 1) {
return 1;
}
Step 3: Recursive Case
- The recursive case involves calling the factorial method with
n-1and multiplying the result byn. This step breaks down the problem into smaller subproblems.
return n * factorial(n - 1);
Complete Solution:
public class FactorialCalculator {
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is " + factorial(number));
}
public static int factorial(int n) {
// Step 2: Base case
if (n == 0 || n == 1) {
return 1;
}
// Step 3: Recursive case
return n * factorial(n - 1);
}
}
Explanation:
- Recursion Concept: The factorial function is defined recursively. To find
5!, the function calculates5 * factorial(4), thenfactorial(4)calculates4 * factorial(3), and so on until it reaches the base case. - Base Case: The recursion stops when
nis 0 or 1. This is essential to prevent infinite recursion and eventually compute the result. - Recursive Case: Each recursive call reduces the problem size, leading to the base case.
Example:
int num = 4;
int result = factorial(num);
System.out.println("Factorial of " + num + " is " + result); // Output: 24
This program demonstrates how to calculate the factorial of a number using recursion. By breaking down the problem into smaller subproblems, recursion provides an elegant solution for calculating factorials in Java.