diff --git a/src/main/java/com/thealgorithms/recursion/FactorialRecursion.java b/src/main/java/com/thealgorithms/recursion/FactorialRecursion.java new file mode 100644 index 000000000000..ac7306da40a1 --- /dev/null +++ b/src/main/java/com/thealgorithms/recursion/FactorialRecursion.java @@ -0,0 +1,37 @@ +package com.thealgorithms.recursion; + +/* + * Factorial of a number n is the product of all positive integers less than + * or equal to n. + * + * n! = n × (n - 1) × (n - 2) × ... × 1 + * + * Examples: + * 0! = 1 + * 1! = 1 + * 5! = 120 + */ + +public final class FactorialRecursion { + + private FactorialRecursion() { + throw new UnsupportedOperationException("Utility class"); + } + + /** + * Computes the factorial of a non-negative integer using recursion. + * + * @param n the number whose factorial is to be computed + * @return factorial of n + * @throws IllegalArgumentException if n is negative + */ + public static long factorial(int n) { + if (n < 0) { + throw new IllegalArgumentException("Factorial is not defined for negative numbers"); + } + if (n <= 1) { + return 1; + } + return n * factorial(n - 1); + } +} diff --git a/src/test/java/com/thealgorithms/recursion/FactorialRecursionTest.java b/src/test/java/com/thealgorithms/recursion/FactorialRecursionTest.java new file mode 100644 index 000000000000..2342a5c565a4 --- /dev/null +++ b/src/test/java/com/thealgorithms/recursion/FactorialRecursionTest.java @@ -0,0 +1,34 @@ +package com.thealgorithms.recursion; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class FactorialRecursionTest { + + @Test + void testFactorialOfZero() { + assertEquals(1, FactorialRecursion.factorial(0)); + } + + @Test + void testFactorialOfOne() { + assertEquals(1, FactorialRecursion.factorial(1)); + } + + @Test + void testFactorialOfPositiveNumber() { + assertEquals(120, FactorialRecursion.factorial(5)); + } + + @Test + void testFactorialOfLargerNumber() { + assertEquals(3628800, FactorialRecursion.factorial(10)); + } + + @Test + void testFactorialOfNegativeNumber() { + assertThrows(IllegalArgumentException.class, () -> FactorialRecursion.factorial(-1)); + } +}