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
39 lines (34 loc) · 1.03 KB
/
Factorial.java
File metadata and controls
39 lines (34 loc) · 1.03 KB
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
33
34
35
36
37
38
39
package com.thealgorithms.divideandconquer;
/**
* Computes the factorial of a non-negative integer using an iterative
* approach to avoid recursion overhead and stack overflow risks.
*
* <p>This implementation improves upon the original recursive version by
* eliminating deep recursion, reducing space complexity from O(n) to O(1),
* and improving runtime efficiency on the JVM.
*
* <p>Time Complexity: O(n)
* <br>Space Complexity: O(1)
*/
public final class Factorial {
private Factorial() {
// Utility class
}
/**
* Returns the factorial of the given non-negative number.
*
* @param n the number to compute factorial for
* @return factorial of n (n!)
* @throws IllegalArgumentException if n is negative
*/
public static long factorial(long n) {
if (n < 0) {
throw new IllegalArgumentException("Negative input not allowed");
}
long result = 1;
for (long i = 2; i <= n; i++) {
result *= i;
}
return result;
}
}