TheAlgorithms/Java · error · IllegalArgumentException

number is negative

Error message

number is negative

What it means

Thrown by FactorialRecursion.factorial(n) when n < 0. Factorial is defined only for non-negative integers; the recursion n * factorial(n-1) would diverge for negatives. n == 0 and n == 1 are both base cases returning 1. Note: no overflow guard — large n silently overflows long before any recursion-depth issue.

Source

Thrown at src/main/java/com/thealgorithms/recursion/FactorialRecursion.java:14

package com.thealgorithms.recursion;

public final class FactorialRecursion {
    private FactorialRecursion() {
    }
    /**
     * Recursive FactorialRecursion Method
     *
     * @param n The number to factorial
     * @return The factorial of the number
     */
    public static long factorial(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("number is negative");
        }
        return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate n >= 0 at the caller.
  2. For large n, also guard against long overflow (factorial > 20 overflows long) — switch to BigInteger if needed.
  3. Ensure intermediate computations like (n - k) stay non-negative before passing to factorial.

Example fix

// before
long f = FactorialRecursion.factorial(n); // n may be negative

// after
if (n < 0) throw new IllegalArgumentException("n must be >= 0");
long f = FactorialRecursion.factorial(n);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) {
    throw new IllegalArgumentException("n must be >= 0");
}
long f = FactorialRecursion.factorial(n);

Type guard

static boolean validFactorialInput(int n) {
    return n >= 0;
}

Try / catch

try {
    long f = FactorialRecursion.factorial(n);
} catch (IllegalArgumentException e) {
    logger.warn("Negative factorial input: {}", n);
}

Prevention

When it happens

Trigger: Call factorial(-1) or any negative n. Values like factorial(30) do NOT throw but overflow long; factorial(1000s) may StackOverflowError instead of this exception.

Common situations: Subtracting from n in a loop that dipped below zero; parsed user input not range-checked; combinatorial code computing n-k with k > n.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/ff452248579b49d3. Report an issue: GitHub.