TheAlgorithms/Java · error · IllegalArgumentException

number is negative

Error message

number is negative

What it means

Thrown by Combinations.factorial when n < 0. Factorial is defined only for non-negative integers; the recursive implementation (n * factorial(n-1)) would recurse indefinitely for negative n since decrementing never reaches the 0/1 base case. The guard converts an infinite recursion into a clear, immediate error.

Source

Thrown at src/main/java/com/thealgorithms/maths/Combinations.java:18

package com.thealgorithms.maths;

/**
 * @see <a href="https://en.wikipedia.org/wiki/Combination">Combination</a>
 */
public final class Combinations {
    private Combinations() {
    }

    /**
     * Calculate of factorial
     *
     * @param n the number
     * @return factorial of given 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);
    }

    /**
     * Calculate combinations
     *
     * @param n first number
     * @param k second number
     * @return combinations of given {@code n} and {@code k}
     */
    public static long combinations(int n, int k) {
        return factorial(n) / (factorial(k) * factorial(n - k));
    }

    /**
     * The above method can exceed limit of long (overflow) when factorial(n) is
     * larger than limits of long variable. Thus even if nCk is within range of

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass a non-negative integer n (>= 0).
  2. Guard the caller: if (n < 0) throw or clamp.
  3. Prefer Combinations.combinations(n, k) which encapsulates factorial internally, rather than calling factorial directly with derived values.

Example fix

// before
long f = Combinations.factorial(count - 1); // count == 0 => -1

// after
long f = Combinations.factorial(Math.max(0, count - 1));
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) {
    throw new IllegalArgumentException("factorial requires n >= 0, got " + n);
}
Combinations.factorial(n);

Type guard

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

Prevention

When it happens

Trigger: Calling factorial(-1) or any negative argument. Common when n is computed from a subtraction (e.g. factorial(a - b)) that can go negative, or when reading an unvalidated value.

Common situations: Arithmetic that derives n from user inputs which can underflow below zero; permutation/combination scaffolding where the order of subtraction is reversed; test data that includes 0 and negatives without filtering.

Related errors


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