Factorial using recursion in Java

What is Factorial?

The factorial of a number n (denoted as n!) is the product of all positive integers up to n. n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n-1) \times (n-2) \times \dots \times 1

Examples:

  • 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 = 120
  • 0!=10! = 1 (by definition)

Recursive Idea

  1. Base case:
    • If n == 0 or n == 1, return 1.
  2. Recursive case:
    • n!=n×(n−1)!n! = n \times (n-1)!

Java Code

public class FactorialRecursion {
    // Recursive method to calculate factorial
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1; // Base case
        }
        return n * factorial(n - 1); // Recursive case
    }

    public static void main(String[] args) {
        int number = 5;
        int result = factorial(number);
        System.out.println("Factorial of " + number + " is: " + result);
    }
}

Output

Factorial of 5 is: 120

Leave a Reply