Skip to content

Commit eb7cc47

Browse files
author
Koushik Sai
committed
Add recursive factorial implementation with tests
1 parent 48e02b3 commit eb7cc47

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.thealgorithms.recursion;
2+
3+
/*
4+
* Factorial of a number n is the product of all positive integers less than
5+
* or equal to n.
6+
*
7+
* n! = n × (n - 1) × (n - 2) × ... × 1
8+
*
9+
* Examples:
10+
* 0! = 1
11+
* 1! = 1
12+
* 5! = 120
13+
*/
14+
15+
public final class FactorialRecursion {
16+
17+
private FactorialRecursion() {
18+
throw new UnsupportedOperationException("Utility class");
19+
}
20+
21+
/**
22+
* Computes the factorial of a non-negative integer using recursion.
23+
*
24+
* @param n the number whose factorial is to be computed
25+
* @return factorial of n
26+
* @throws IllegalArgumentException if n is negative
27+
*/
28+
public static long factorial(int n) {
29+
if (n < 0) {
30+
throw new IllegalArgumentException("Factorial is not defined for negative numbers");
31+
}
32+
if (n <= 1) {
33+
return 1;
34+
}
35+
return n * factorial(n - 1);
36+
}
37+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.recursion;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
import org.junit.jupiter.api.Test;
6+
7+
class FactorialRecursionTest {
8+
9+
@Test
10+
void testFactorialOfZero() {
11+
assertEquals(1, FactorialRecursion.factorial(0));
12+
}
13+
14+
@Test
15+
void testFactorialOfOne() {
16+
assertEquals(1, FactorialRecursion.factorial(1));
17+
}
18+
19+
@Test
20+
void testFactorialOfPositiveNumber() {
21+
assertEquals(120, FactorialRecursion.factorial(5));
22+
}
23+
24+
@Test
25+
void testFactorialOfLargerNumber() {
26+
assertEquals(3628800, FactorialRecursion.factorial(10));
27+
}
28+
29+
@Test
30+
void testFactorialOfNegativeNumber() {
31+
assertThrows(IllegalArgumentException.class,
32+
() -> FactorialRecursion.factorial(-1));
33+
}
34+
}

0 commit comments

Comments
 (0)