diff --git a/src/main/java/com/thealgorithms/recursion/Factorial.java b/src/main/java/com/thealgorithms/recursion/Factorial.java new file mode 100644 index 000000000000..63ffcf1feb96 --- /dev/null +++ b/src/main/java/com/thealgorithms/recursion/Factorial.java @@ -0,0 +1,32 @@ +package com.thealgorithms.recursion; + +/* + The Factorial of a non-negative integer n is the product of all positive integers less than or + equal to n. It is defined as: n! = n × (n - 1) × (n - 2) × ... × 1 with the base case: 0! = 1 + + Example: + 5! = 5 × 4 × 3 × 2 × 1 = 120 +*/ + +public final class Factorial { + private Factorial() { + throw new UnsupportedOperationException("Utility class"); + } + + /** + * Computes the factorial of a non-negative integer using recursion. + * + * @param n the number for which factorial is to be calculated + * @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 == 0 || n == 1) { + return 1; + } + return n * factorial(n - 1); + } +} diff --git a/src/test/java/com/thealgorithms/recursion/FactorialTest.java b/src/test/java/com/thealgorithms/recursion/FactorialTest.java new file mode 100644 index 000000000000..ac69bcfba152 --- /dev/null +++ b/src/test/java/com/thealgorithms/recursion/FactorialTest.java @@ -0,0 +1,35 @@ +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; + +public class FactorialTest { + @Test + public void testFactorialOfZero() { + assertEquals(1, Factorial.factorial(0)); + } + + @Test + public void testFactorialOfOne() { + assertEquals(1, Factorial.factorial(1)); + } + + @Test + public void testFactorialOfPositiveNumbers() { + assertEquals(120, Factorial.factorial(5)); + assertEquals(720, Factorial.factorial(6)); + assertEquals(5040, Factorial.factorial(7)); + } + + @Test + public void testFactorialOfTen() { + assertEquals(3628800, Factorial.factorial(10)); + } + + @Test + public void testNegativeNumberThrowsException() { + assertThrows(IllegalArgumentException.class, () -> Factorial.factorial(-1)); + } +} \ No newline at end of file