TheAlgorithms/Java · error · IllegalArgumentException

Input must be non-negative

Error message

Input must be non-negative

What it means

Thrown by SieveOfEratosthenes.findPrimes(int n) when n is negative. The sieve allocates a boolean[] of size n+1 and indexes from index 2; a negative n would produce a malformed array and meaningless iteration, so the guard rejects it up front. n in [0,1] returns an empty list rather than throwing.

Source

Thrown at src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java:39

 * @author Navadeep0007
 * @see <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a>
 */
public final class SieveOfEratosthenes {

    private SieveOfEratosthenes() {
        // Utility class, prevent instantiation
    }

    /**
     * Finds all prime numbers up to n using the Sieve of Eratosthenes algorithm
     *
     * @param n the upper limit (inclusive)
     * @return a list of all prime numbers from 2 to n
     * @throws IllegalArgumentException if n is negative
     */
    public static List<Integer> findPrimes(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Input must be non-negative");
        }

        if (n < 2) {
            return new ArrayList<>();
        }

        // Create boolean array, initially all true
        boolean[] isPrime = new boolean[n + 1];
        for (int i = 2; i <= n; i++) {
            isPrime[i] = true;
        }

        // Sieve process
        for (int i = 2; i * i <= n; i++) {
            if (isPrime[i]) {
                // Mark all multiples of i as not prime
                for (int j = i * i; j <= n; j += i) {
                    isPrime[j] = false;

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate/abs the input or return an empty result for negative bounds at the call site.
  2. Use Math.max(0, n) before calling if negatives are tolerable as 'no primes'.
  3. Add an assertion/precondition in the caller documenting the non-negative contract.

Example fix

// before
List<Integer> primes = SieveOfEratosthenes.findPrimes(limit);

// after
List<Integer> primes = SieveOfEratosthenes.findPrimes(Math.max(0, limit));
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) throw new IllegalArgumentException("n must be >= 0");
List<Integer> primes = SieveOfEratosthenes.findPrimes(n);

Prevention

When it happens

Trigger: Call findPrimes(-1), findPrimes(-100), or pass a value computed as (a - b) where the subtraction went negative unexpectedly.

Common situations: Untested user input, a bound expression that underflows (e.g., size - margin with margin > size), or porting code that assumed unsigned arithmetic.

Related errors


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