TheAlgorithms/Python · error · ValueError

Divisor a must be a positive integer

Error message

Divisor a must be a positive integer

What it means

Raised by modular_division() in maths/modular_division.py when the divisor a <= 0. The function computes b * a^(-1) mod n using the modular inverse of a, which it defines only for positive a; zero has no inverse and negative divisors are not handled by this implementation.

Source

Thrown at maths/modular_division.py:34


    This find x = b*a^(-1) mod n
    Uses ExtendedEuclid to find the inverse of a

    >>> modular_division(4,8,5)
    2

    >>> modular_division(3,8,5)
    1

    >>> modular_division(4, 11, 5)
    4

    """
    if n <= 1:
        raise ValueError("Modulus n must be greater than 1")
    if a <= 0:
        raise ValueError("Divisor a must be a positive integer")
    if greatest_common_divisor(a, n) != 1:
        raise ValueError("a and n must be coprime (gcd(a, n) = 1)")

    (_d, _t, s) = extended_gcd(n, a)  # Implemented below
    x = (b * s) % n
    return x


def invert_modulo(a: int, n: int) -> int:
    """
    This function find the inverses of a i.e., a^(-1)

    >>> invert_modulo(2, 5)
    3

    >>> invert_modulo(8,7)
    1

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a positive divisor: modular_division(4, 8, 5).
  2. If a can be negative, reduce it first: a = a % n (Python's % yields a value in [0, n)).
  3. Guard against a == 0 before calling — zero has no modular inverse by definition.

Example fix

# before
modular_division(-4, 8, 5)

# after
a = -4 % 5  # a == 1
modular_division(a, 8, 5)
Defensive patterns

Strategy: validation

Validate before calling

a = a % n  # normalizes a into [0, n)
if a == 0:
    raise ValueError('divisor is 0 mod n and has no inverse')

Prevention

When it happens

Trigger: modular_division(0, 8, 5) (zero divisor), modular_division(-4, 8, 5) (negative divisor), or argument-order mix-ups placing a non-positive value first.

Common situations: Divisor computed as a difference that can be zero or negative, sign errors in upstream arithmetic, or forgetting that this API requires a strictly positive a.

Related errors


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