TheAlgorithms/Python · error · ValueError
Only positive numbers are accepted
Error message
Only positive numbers are accepted
What it means
number_of_divisors() counts divisors via factorization. Divisor count is only defined for positive integers, so n <= 0 raises ValueError('Only positive numbers are accepted').
Source
Thrown at maths/basic_maths.py:48
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)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
>>> number_of_divisors(-10)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
"""
if n <= 0:
raise ValueError("Only positive numbers are accepted")
div = 1
temp = 1
while n % 2 == 0:
temp += 1
n = int(n / 2)
div *= temp
for i in range(3, int(math.sqrt(n)) + 1, 2):
temp = 1
while n % i == 0:
temp += 1
n = int(n / i)
div *= temp
if n > 1:
div *= 2
return div
def sum_of_divisors(n: int) -> int:
View on GitHub (pinned to f5988cc097)
Solutions
- Start loops at 1 (range(1, n + 1)) when enumerating candidates.
- Validate n > 0 at the input boundary.
- Special-case 0 explicitly if your domain needs it, since the library will not.
Example fix
# before
for i in range(0, 101):
d = number_of_divisors(i) # fails at i=0
# after
for i in range(1, 101):
d = number_of_divisors(i) Defensive patterns
Strategy: validation
Validate before calling
if n <= 0:
raise ValueError(f"n must be positive, got {n}")
count = number_of_divisors(n) Type guard
def is_positive_int(n: object) -> bool:
return isinstance(n, int) and n > 0 Prevention
- Start enumeration loops at 1, never 0
- Share one positivity guard across all basic_maths call sites
When it happens
Trigger: number_of_divisors(0); number_of_divisors(-10); any range iteration that includes 0, e.g. loop over range(0, n) calling the function.
Common situations: Iterating over sequences that start at 0; accepting negative user input; reuse of the same n across several basic_maths functions where 0 slipped through.
Related errors
- Input must be positive
- Only positive integers have prime factors
- Limit for the Catalan sequence must be ≥ 0
- Number should not be negative.
- Negative arguments are not supported
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/3901600e8a731281.
Report an issue: GitHub.