{"record":{"id":"a9a3d420f5fa6ebf","repo":"TheAlgorithms/Python","slug":"divisor-a-must-be-a-positive-integer","errorCode":null,"errorMessage":"Divisor a must be a positive integer","messagePattern":"Divisor a must be a positive integer","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/modular_division.py","lineNumber":34,"sourceCode":"\n\n    This find x = b*a^(-1) mod n\n    Uses ExtendedEuclid to find the inverse of a\n\n    >>> modular_division(4,8,5)\n    2\n\n    >>> modular_division(3,8,5)\n    1\n\n    >>> modular_division(4, 11, 5)\n    4\n\n    \"\"\"\n    if n <= 1:\n        raise ValueError(\"Modulus n must be greater than 1\")\n    if a <= 0:\n        raise ValueError(\"Divisor a must be a positive integer\")\n    if greatest_common_divisor(a, n) != 1:\n        raise ValueError(\"a and n must be coprime (gcd(a, n) = 1)\")\n\n    (_d, _t, s) = extended_gcd(n, a)  # Implemented below\n    x = (b * s) % n\n    return x\n\n\ndef invert_modulo(a: int, n: int) -> int:\n    \"\"\"\n    This function find the inverses of a i.e., a^(-1)\n\n    >>> invert_modulo(2, 5)\n    3\n\n    >>> invert_modulo(8,7)\n    1\n","sourceCodeStart":16,"sourceCodeEnd":52,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/modular_division.py#L16-L52","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Pass a positive divisor: modular_division(4, 8, 5).","If a can be negative, reduce it first: a = a % n (Python's % yields a value in [0, n)).","Guard against a == 0 before calling — zero has no modular inverse by definition."],"exampleFix":"# before\nmodular_division(-4, 8, 5)\n\n# after\na = -4 % 5  # a == 1\nmodular_division(a, 8, 5)","handlingStrategy":"validation","validationCode":"a = a % n  # normalizes a into [0, n)\nif a == 0:\n    raise ValueError('divisor is 0 mod n and has no inverse')","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Reduce divisors mod n before dividing.","Reject zero divisors at input; they are never invertible."],"tags":["math","number-theory","valueerror","modular-arithmetic"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}