TheAlgorithms/Python · error · ValueError

Number {n} must instead be a positive integer

Error message

Number {n} must instead be a positive integer

What it means

sieve() in maths/segmented_sieve.py implements a segmented Sieve of Eratosthenes for primes up to n. It raises ValueError(f'Number {n} must instead be a positive integer') when n <= 0 or isinstance(n, float). Floats are rejected explicitly (unlike some sibling sieves) because int(math.sqrt(n)) and the segment arithmetic assume exact integers; the message interpolates the offending value, e.g. 'Number 22.2 must instead be a positive integer'.

Source

Thrown at maths/segmented_sieve.py:35

    >>> sieve(0)
    Traceback (most recent call last):
        ...
    ValueError: Number 0 must instead be a positive integer

    >>> sieve(-1)
    Traceback (most recent call last):
        ...
    ValueError: Number -1 must instead be a positive integer

    >>> sieve(22.2)
    Traceback (most recent call last):
        ...
    ValueError: Number 22.2 must instead be a positive integer
    """

    if n <= 0 or isinstance(n, float):
        msg = f"Number {n} must instead be a positive integer"
        raise ValueError(msg)

    in_prime = []
    start = 2
    end = int(math.sqrt(n))  # Size of every segment
    temp = [True] * (end + 1)
    prime = []

    while start <= end:
        if temp[start] is True:
            in_prime.append(start)
            for i in range(start * start, end + 1, start):
                temp[i] = False
        start += 1
    prime += in_prime

    low = end + 1
    high = min(2 * end, n)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Ensure the bound is an int and >= 1: sieve(int(n)) after a positivity check.
  2. Compute bounds with integer operations (len(x), //, max+1) rather than / which yields floats.
  3. Validate n >= 1 (and not float) upstream with your own error if the bound is external.

Example fix

# before
sieve(upper * 1.0)  # ValueError: Number 22.0 must instead be a positive integer

# after
sieve(int(upper))
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(n, int) or n < 1:
    n = int(n)
    if n < 1:
        raise ValueError(f'bad sieve bound: {n}')
sieve(n)

Type guard

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

Prevention

When it happens

Trigger: Calling sieve(-1), sieve(0), or sieve(22.2). Note 22.0 is also rejected — any float fails the isinstance check even when integral.

Common situations: Passing a normalized ratio or averaged bound (always float); a computed upper bound that hits 0 on empty input; mixing this sieve with other algorithms in the repo whose float handling differs, so code 'that worked over there' fails here.

Related errors


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