TheAlgorithms/Python · error · ValueError

Modulus n must be greater than 1

Error message

Modulus n must be greater than 1

What it means

Raised by modular_division() in maths/modular_division.py when the modulus n <= 1. Modular arithmetic modulo 1 (or 0/negative) is degenerate — every value is congruent to 0 — and the inverse computation via extended_gcd would be meaningless, so the function rejects it up front.

Source

Thrown at maths/modular_division.py:32

    Theorem:
    a has a multiplicative inverse modulo n iff gcd(a,n) = 1


    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)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Supply n >= 2, e.g. modular_division(4, 8, 5).
  2. Check the parameter order: the signature is (a, b, n) with n last.
  3. Validate modulus at input: if n < 2: reject with your own error before calling.

Example fix

# before
modular_division(4, 8, 1)

# after
modular_division(4, 8, 5)
Defensive patterns

Strategy: validation

Validate before calling

if n < 2:
    raise ValueError('modulus must be an integer >= 2')

Prevention

When it happens

Trigger: modular_division(a, b, 1), modular_division(a, b, 0), or any call where the modulus defaults to 0 and is never set, e.g. modular_division(4, 8, n) with n initialized to 0.

Common situations: Passing a modulus from unvalidated user input, misreading the argument order (n where a is expected), or test code that exercises edge moduli.

Related errors


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