TheAlgorithms/Python · error · ValueError

Modulus must be a positive integer

Error message

Modulus must be a positive integer

What it means

In binary_exp_mod_recursive, after the exponent passes validation, a modulus <= 0 raises ValueError('Modulus must be a positive integer'). Modular arithmetic requires a positive modulus for well-defined residues.

Source

Thrown at maths/binary_exponentiation.py:113

    >>> binary_exp_mod_recursive(3, 4, 5)
    1
    >>> binary_exp_mod_recursive(11, 13, 7)
    4
    >>> binary_exp_mod_recursive(1.5, 4, 3)
    2.0625
    >>> binary_exp_mod_recursive(7, -1, 10)
    Traceback (most recent call last):
        ...
    ValueError: Exponent must be a non-negative integer
    >>> binary_exp_mod_recursive(7, 13, 0)
    Traceback (most recent call last):
        ...
    ValueError: Modulus must be a positive integer
    """
    if exponent < 0:
        raise ValueError("Exponent must be a non-negative integer")
    if modulus <= 0:
        raise ValueError("Modulus must be a positive integer")

    if exponent == 0:
        return 1

    if exponent % 2 == 1:
        return (binary_exp_mod_recursive(base, exponent - 1, modulus) * base) % modulus

    r = binary_exp_mod_recursive(base, exponent // 2, modulus)
    return (r * r) % modulus


def binary_exp_mod_iterative(base: float, exponent: int, modulus: int) -> float:
    """
    Computes a^b % c iteratively, where a is the base, b is the exponent, and c is the
    modulus

    >>> binary_exp_mod_iterative(3, 4, 5)
    1

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a positive modulus (>= 1); modulus 1 is legal and always yields 0.
  2. Check argument order — signature is (base, exponent, modulus).
  3. Validate the modulus at configuration load time.

Example fix

# before
result = binary_exp_mod_recursive(base, modulus, exponent)  # wrong order

# after
result = binary_exp_mod_recursive(base, exponent, modulus)
Defensive patterns

Strategy: validation

Validate before calling

if modulus <= 0:
    raise ValueError(f"modulus must be >= 1, got {modulus}")
result = binary_exp_mod_recursive(base, exponent, modulus)

Type guard

def is_positive_int(m: object) -> bool:
    return isinstance(m, int) and m >= 1

Prevention

When it happens

Trigger: binary_exp_mod_recursive(7, 13, 0); binary_exp_mod_recursive(7, 13, -5); modulus read from config as 0 default, or a modulus variable never initialized from its argument.

Common situations: Default-initialized modulus left at 0; passing (base, modulus, exponent) in the wrong order so 0 or a negative lands in the modulus slot; modulus computed as a difference that can be 0.

Related errors


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