TheAlgorithms/Java · error · IllegalArgumentException

n must be non-negative.

Error message

n must be non-negative.

What it means

Thrown by NthUglyNumber.get(int n) when n is negative. The method lazily generates ugly numbers up to index n and caches them; a negative index is meaningless for a zero-based sequence and would break the generation loop. The guard fires before the while-loop that populates the cache.

Source

Thrown at src/main/java/com/thealgorithms/maths/NthUglyNumber.java:45

     */
    NthUglyNumber(final int[] baseNumbers) {
        if (baseNumbers.length == 0) {
            throw new IllegalArgumentException("baseNumbers must be non-empty.");
        }

        for (final var baseNumber : baseNumbers) {
            this.positions.add(MutablePair.of(baseNumber, 0));
        }
    }

    /**
     * @param n the zero-based-index of the queried ugly number
     * @exception IllegalArgumentException n is negative
     * @return the n-th ugly number (starting from index 0)
     */
    public Long get(final int n) {
        if (n < 0) {
            throw new IllegalArgumentException("n must be non-negative.");
        }

        while (uglyNumbers.size() <= n) {
            addUglyNumber();
        }

        return uglyNumbers.get(n);
    }

    private void addUglyNumber() {
        uglyNumbers.add(computeMinimalCandidate());
        updatePositions();
    }

    private void updatePositions() {
        final var lastUglyNumber = uglyNumbers.get(uglyNumbers.size() - 1);
        for (var entry : positions) {
            if (computeCandidate(entry) == lastUglyNumber) {

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Clamp or reject the index at the caller: if (n < 0) handle the invalid request.
  2. Fix the upstream arithmetic producing the negative value (check loop bounds, length calculations).
  3. If a negative index should map to something meaningful in your domain, remap it before calling get.

Example fix

// before
Long val = ugly.get(requestedIndex);

// after
if (requestedIndex < 0) {
    throw new IndexOutOfBoundsException("index " + requestedIndex);
}
Long val = ugly.get(requestedIndex);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) {
    throw new IllegalArgumentException("n must be >= 0: " + n);
}
Long val = ugly.get(n);

Prevention

When it happens

Trigger: Calling get(-1), get(-5), or any get(n) where n < 0. Common when n is computed from an expression like (count - k) that can go negative.

Common situations: User-supplied index not sanitized before the call; off-by-one in a loop bound (e.g., loop from n down to 0 inclusive when it should be exclusive); arithmetic on array lengths producing a negative result; parsed integer from a request payload that accepted negatives.

Related errors


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