TheAlgorithms/Python · error · ValueError

Please enter an integer greater than 0

Error message

Please enter an integer greater than 0

What it means

Raised by solution() in project_euler/problem_069/sol1.py when n <= 0. The function builds a sieve-based totient table phi = list(range(n + 1)); a non-positive n makes the table (and the max n/phi(n) search over 1..n) meaningless, so it refuses immediately. Note n is not type-checked here, so a float like 10.5 would cause a different failure downstream.

Source

Thrown at project_euler/problem_069/sol1.py:48

    Algorithm:
    1. Precompute φ(k) for all natural k, k <= n using product formula (wikilink below)
    https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler's_product_formula

    2. Find k/φ(k) for all k ≤ n and return the k that attains maximum

    >>> solution(10)
    6

    >>> solution(100)
    30

    >>> solution(9973)
    2310

    """

    if n <= 0:
        raise ValueError("Please enter an integer greater than 0")

    phi = list(range(n + 1))
    for number in range(2, n + 1):
        if phi[number] == number:
            phi[number] -= 1
            for multiple in range(number * 2, n + 1, number):
                phi[multiple] = (phi[multiple] // number) * (number - 1)

    answer = 1
    for number in range(1, n + 1):
        if (answer / phi[answer]) < (number / phi[number]):
            answer = number

    return answer


if __name__ == "__main__":
    print(solution())

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a positive integer bound: solution(10), solution(1000000).
  2. Guard computed bounds at the call site: if bound <= 0: raise/skip.
  3. Fix the upstream variable that produced 0 (missing env var, empty input).

Example fix

# before
bound = limit - offset  # can be <= 0
best = solution(bound)

# after
if bound <= 0:
    raise ValueError(f"bound must be positive, got {bound}")
best = solution(bound)
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(n, int) or n <= 0:
    raise ValueError(f"n must be a positive int, got {n!r}")
solution(n)

Type guard

def is_positive_int(value) -> bool:
    return isinstance(value, int) and value > 0

Try / catch

try:
    answer = solution(n)
except ValueError as e:
    if "greater than 0" in str(e):
        answer = None  # or a sensible default for your use case
    else:
        raise

Prevention

When it happens

Trigger: solution(0), solution(-10), or callers forwarding a computed bound that collapsed to 0 (e.g. solution(limit - delta) where delta >= limit).

Common situations: Parameterized test sweeps that include 0 or negative bounds; config values parsed as 0 when a variable is unset; arithmetic on limits (subtraction/rounding) producing <= 0.

Related errors


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