Factorial Recursion Algorithm

The Factorial Recursion Algorithm is a widely used technique in computer science and mathematics for solving the factorial of a given number. The factorial of a non-negative integer n, denoted by n! is the product of all positive integers less than or equal to n. For instance, the factorial of 5 (5!) is equal to 5 * 4 * 3 * 2 * 1 = 120. The algorithm uses the principle of recursion, which is a programming paradigm where a function calls itself in its definition, resulting in a series of smaller repetitive problems. In the case of the factorial recursion algorithm, the function computes the factorial of the given number by multiplying it with the factorial of the number one less than it, and continues to do so until the base case is reached (0! or 1!). The base case in the algorithm is crucial to ensure the recursion terminates, and it is defined as 0! = 1! = 1. When the function is called with an input of 0 or 1, it returns the value 1, preventing the recursion from going indefinitely. The recursion proceeds by breaking the problem down into smaller subproblems, where the factorial of a given number n is computed as the product of n and the factorial of n-1. This process continues until the base case is encountered, at which point the recursion starts to unwind, and the function returns the product of all the integers from n down to 1. The factorial recursion algorithm is elegant and easy to understand, but it may not be the most efficient method for solving large factorial problems due to the overhead of recursive function calls and the potential for stack overflow issues in some programming languages.
package Maths;

public class FactorialRecursion {

    /* Driver Code */
    public static void main(String[] args) {
        assert factorial(0) == 1;
        assert factorial(1) == 1;
        assert factorial(2) == 2;
        assert factorial(3) == 6;
        assert factorial(5) == 120;
    }

    /**
     * Recursive FactorialRecursion Method
     *
     * @param n The number to factorial
     * @return The factorial of the number
     */
    public static long factorial(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("number is negative");
        }
        return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
    }
}

LANGUAGE:

DARK MODE: