Find the Factorial of a Number Using Recursion

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 of n-1 and then multiplying it by n.

Step 2: Base Case

  • The base case is crucial for terminating the recursion. For factorial, the base case is when n is 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-1 and multiplying the result by n. 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 calculates 5 * factorial(4), then factorial(4) calculates 4 * factorial(3), and so on until it reaches the base case.
  • Base Case: The recursion stops when n is 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.