File tree Expand file tree Collapse file tree 2 files changed +71
-0
lines changed
main/java/com/thealgorithms/recursion
test/java/com/thealgorithms/recursion Expand file tree Collapse file tree 2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments