Skip to content
23 changes: 23 additions & 0 deletions src/main/java/com/thealgorithms/recursion/Factorial.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
29 changes: 29 additions & 0 deletions src/test/java/com/thealgorithms/recursion/FactorialTest.java
Original file line number Diff line number Diff line change
@@ -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));
}
}