Skip to content

Commit 1c69e7f

Browse files
committed
added factorial using recursion
1 parent f0fb971 commit 1c69e7f

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.recursion;
2+
3+
/*
4+
The Factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
5+
It is defined as:
6+
n! = n × (n - 1) × (n - 2) × ... × 1
7+
with the base case:
8+
0! = 1
9+
10+
Example:
11+
5! = 5 × 4 × 3 × 2 × 1 = 120
12+
*/
13+
14+
public final class Factorial {
15+
16+
private Factorial() {
17+
throw new UnsupportedOperationException("Utility class");
18+
}
19+
20+
/**
21+
* Computes the factorial of a non-negative integer using recursion.
22+
*
23+
* @param n the number for which factorial is to be calculated
24+
* @return factorial of n
25+
* @throws IllegalArgumentException if n is negative
26+
*/
27+
public static long factorial(int n) {
28+
if (n < 0) {
29+
throw new IllegalArgumentException("Factorial is not defined for negative numbers.");
30+
}
31+
if (n == 0 || n == 1) {
32+
return 1;
33+
}
34+
return n * factorial(n - 1);
35+
}
36+
}

0 commit comments

Comments
 (0)