TheAlgorithms/Python · error · ValueError

Input must be a positive integer

Error message

Input must be a positive integer

What it means

prime_sieve_eratosthenes() in maths/prime_sieve_eratosthenes.py returns all primes <= num via the classic sieve. It raises ValueError('Input must be a positive integer') when num <= 0, because primes[True] * (num + 1) would build an empty/negative-length list and the sieve loop would be meaningless. num == 1 is legal and returns [] (no primes <= 1); the rejection starts at 0 and below.

Source

Thrown at maths/prime_sieve_eratosthenes.py:34

    """
    Print the prime numbers up to n

    >>> prime_sieve_eratosthenes(10)
    [2, 3, 5, 7]
    >>> prime_sieve_eratosthenes(20)
    [2, 3, 5, 7, 11, 13, 17, 19]
    >>> prime_sieve_eratosthenes(2)
    [2]
    >>> prime_sieve_eratosthenes(1)
    []
    >>> prime_sieve_eratosthenes(-1)
    Traceback (most recent call last):
    ...
    ValueError: Input must be a positive integer
    """

    if num <= 0:
        raise ValueError("Input must be a positive integer")

    primes = [True] * (num + 1)

    p = 2
    while p * p <= num:
        if primes[p]:
            for i in range(p * p, num + 1, p):
                primes[i] = False
        p += 1

    return [prime for prime in range(2, num + 1) if primes[prime]]


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check the bound before calling: raise or default when num < 1 in your own code.
  2. Ensure limit-producing expressions (max(), len()-1, a-b) cannot go non-positive on degenerate inputs.
  3. Catch ValueError when the limit is external user input.

Example fix

# before
primes = prime_sieve_eratosthenes(limit)  # ValueError when limit == 0

# after
limit = max(1, limit)
primes = prime_sieve_eratosthenes(limit)
Defensive patterns

Strategy: validation

Validate before calling

if num < 1:
    raise ValueError(f'upper bound must be >= 1, got {num}')
prime_sieve_eratosthenes(num)

Type guard

def is_sieve_bound(v) -> bool:
    return isinstance(v, int) and v >= 1

Prevention

When it happens

Trigger: Calling prime_sieve_eratosthenes(-1) or prime_sieve_eratosthenes(0). Note floats like 2.0 are NOT rejected here — [True] * (2.0 + 1) would fail differently — so the documented guard covers only the <= 0 case.

Common situations: Passing an upper bound computed as max(list) - 1 on empty lists (yields negative), a user-supplied limit that defaults to 0, or an off-by-one that lands at 0.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/b1e6c3a6e0c67be2. Report an issue: GitHub.