forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorial.java
More file actions
32 lines (29 loc) · 847 Bytes
/
Factorial.java
File metadata and controls
32 lines (29 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.thealgorithms.recursion;
/**
* Implementation of factorial using recursion.
* <p>
* The factorial of a non-negative integer n is defined as:
* n! = n × (n-1) × (n-2) × ... × 1, with 0! = 1.
*/
public final class Factorial {
// Private constructor to prevent instantiation
private Factorial() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Calculates factorial recursively.
*
* @param n non-negative integer
* @return factorial of n
* @throws IllegalArgumentException if n is negative
*/
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Number must be non-negative");
}
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
}