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..5144469743d3 --- /dev/null +++ b/src/main/java/com/thealgorithms/recursion/Factorial.java @@ -0,0 +1,23 @@ +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..f5783f7c57a7 --- /dev/null +++ b/src/test/java/com/thealgorithms/recursion/FactorialTest.java @@ -0,0 +1,29 @@ +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 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)); + } +}