TheAlgorithms/Java · error · IllegalArgumentException

Input 'n' must be a non-negative integer.

Error message

Input 'n' must be a non-negative integer.

What it means

Thrown by FibonacciLoop.compute when n < 0. The method computes the nth Fibonacci number iteratively; the sequence F(0)=0, F(1)=1 is defined for non-negative indices only, and the for loop `for (i = 2; i <= n; i++)` would not execute for negative n (silently returning via the n <= 1 branch with a wrong sign), so the guard rejects negatives explicitly.

Source

Thrown at src/main/java/com/thealgorithms/maths/FibonacciLoop.java:34

 * <li>{@link com.thealgorithms.matrix.matrixexponentiation.Fibonacci} - O(log n) Matrix Exponentiation approach</li>
 * </ul>
 */
public final class FibonacciLoop {

    private FibonacciLoop() {
        // Private constructor to prevent instantiation of this utility class.
    }

    /**
     * Calculates the nth Fibonacci number.
     *
     * @param n The index of the Fibonacci number to calculate.
     * @return The nth Fibonacci number as a BigInteger.
     * @throws IllegalArgumentException if the input 'n' is a negative integer.
     */
    public static BigInteger compute(final int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Input 'n' must be a non-negative integer.");
        }

        if (n <= 1) {
            return BigInteger.valueOf(n);
        }

        BigInteger prev = BigInteger.ZERO;
        BigInteger current = BigInteger.ONE;

        for (int i = 2; i <= n; i++) {
            BigInteger next = prev.add(current);
            prev = current;
            current = next;
        }

        return current;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass a non-negative int n (>= 0); compute(0) returns 0, compute(1) returns 1.
  2. Validate at the caller: if (n < 0) reject before calling.
  3. Clamp derived indices with Math.max(0, n).

Example fix

// before
BigInteger f = FibonacciLoop.compute(rank - 1); // rank == 0 => -1

// after
BigInteger f = FibonacciLoop.compute(Math.max(0, rank - 1));
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) {
    throw new IllegalArgumentException("Fibonacci index must be >= 0");
}
FibonacciLoop.compute(n);

Type guard

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

Prevention

When it happens

Trigger: Calling compute(-1) or any negative n. Common when n is derived from a subtraction or parsed from unvalidated input.

Common situations: n computed as a difference that underflows; user input not bounded; loop boundaries that dip below zero; off-by-one in index arithmetic.

Related errors


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