TheAlgorithms/Python · error · ValueError

Only positive integers have prime factors

Error message

Only positive integers have prime factors

What it means

prime_factors() returns the prime factorization of n by trial division. It raises ValueError('Only positive integers have prime factors') for n <= 0 because factorization is only defined for positive integers.

Source

Thrown at maths/basic_maths.py:20

import math


def prime_factors(n: int) -> list:
    """Find Prime Factors.
    >>> prime_factors(100)
    [2, 2, 5, 5]
    >>> prime_factors(0)
    Traceback (most recent call last):
        ...
    ValueError: Only positive integers have prime factors
    >>> prime_factors(-10)
    Traceback (most recent call last):
        ...
    ValueError: Only positive integers have prime factors
    """
    if n <= 0:
        raise ValueError("Only positive integers have prime factors")
    pf = []
    while n % 2 == 0:
        pf.append(2)
        n = int(n / 2)
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            pf.append(i)
            n = int(n / i)
    if n > 2:
        pf.append(n)
    return pf


def number_of_divisors(n: int) -> int:
    """Calculate Number of Divisors of an Integer.
    >>> number_of_divisors(100)
    9
    >>> number_of_divisors(0)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Filter or reject n <= 0 before calling.
  2. Use abs(n) only if negative input is genuinely meaningful in your domain (it changes semantics).
  3. Treat 0 and negatives as invalid data at the parse boundary, not deep in the math call.

Example fix

# before
factors = prime_factors(n)

# after
if n <= 0:
    raise ValueError(f"expected positive integer, got {n}")
factors = prime_factors(n)
Defensive patterns

Strategy: validation

Validate before calling

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

Type guard

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

Prevention

When it happens

Trigger: prime_factors(0); prime_factors(-10); any n <= 0 reaching the function from user input or a computation that underflowed to/below zero.

Common situations: Parsing signed input; loops that decrement a counter past 1; zero sentinels used to mean 'no value' but passed through to math code.

Related errors


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