TheAlgorithms/Java · error · IllegalArgumentException
Input number cannot be negative
Error message
Input number cannot be negative
What it means
Thrown by Factorial.factorial when n < 0. Factorial is defined for non-negative integers; the iterative loop `for (i = 1; i <= n; i++)` would not execute for negative n and would silently return 1 (wrong), so the library rejects negatives explicitly to avoid a silently incorrect result.
Source
Thrown at src/main/java/com/thealgorithms/maths/Factorial.java:11
package com.thealgorithms.maths;
import java.math.BigInteger;
public final class Factorial {
private Factorial() {
}
public static BigInteger factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input number cannot be negative");
}
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Pass a non-negative integer n (>= 0); factorial(0) correctly returns 1.
- Guard at the caller: if (n < 0) reject or clamp to 0.
- Validate parsed input before invoking.
Example fix
// before BigInteger f = Factorial.factorial(count - 1); // count == 0 => -1 // after BigInteger f = Factorial.factorial(Math.max(0, count - 1));
Defensive patterns
Strategy: validation
Validate before calling
if (n < 0) {
throw new IllegalArgumentException("factorial requires n >= 0");
}
Factorial.factorial(n); Type guard
static boolean isNonNegative(int n) { return n >= 0; } Prevention
- Guard factorial(a - b) with Math.max(0, a - b).
- Validate parsed integers before calling.
- Remember factorial(0) is valid and returns 1.
When it happens
Trigger: Calling factorial(-1) or any negative n. Common when n is derived from a subtraction or parsed from unvalidated input.
Common situations: n computed as a - b that can go negative; user input not bounded; loop boundaries that include 0 or below; off-by-one in decrementing logic.
Related errors
- Must be a natural number
- number is negative
- Input must be a positive integer.
- Input must me positive.
- n must be positive and odd.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/46c3af7f6ab75f3c.
Report an issue: GitHub.