Class Factorial
java.lang.Object
topics.divideconquer.factorial.Factorial
Factorial Calculation
Demonstrates both the iterative and recursive paradigms for computing the factorial of a non-negative integer (N!).
*The Integer Overflow Trap
Factorial functions grow explosively.
- Using standard 32-bit
int, the maximum computable value is 12! - At 13!, the value exceeds 2.14 billion and causes a silent arithmetic overflow.
- By upgrading to 64-bit
long, this implementation safely computes up to 20!
BigInteger class must be used.
- Author:
- vicegd
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionlongfactorialIterative(int n) Iterative implementation using a linear accumulator.longfactorialRecursive(int n) Recursive implementation demonstrating Divide and Conquer by Subtraction.
-
Constructor Details
-
Factorial
public Factorial()
-
-
Method Details
-
factorialIterative
public long factorialIterative(int n) Iterative implementation using a linear accumulator.- Time Complexity:
O(N) - Space Complexity:
O(1)
- Parameters:
n- A non-negative integer up to 20.- Returns:
- The factorial of N.
- Throws:
IllegalArgumentException- if N is negative.
- Time Complexity:
-
factorialRecursive
public long factorialRecursive(int n) Recursive implementation demonstrating Divide and Conquer by Subtraction.- Time Complexity:
O(N) - Space Complexity:
O(N)due to the execution call stack.
- Parameters:
n- A non-negative integer up to 20.- Returns:
- The factorial of N.
- Throws:
IllegalArgumentException- if N is negative.
- Time Complexity:
-