{"record":{"id":"4d3a7c9095c8da96","repo":"TheAlgorithms/Python","slug":"modulus-n-must-be-greater-than-1","errorCode":null,"errorMessage":"Modulus n must be greater than 1","messagePattern":"Modulus n must be greater than 1","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/modular_division.py","lineNumber":32,"sourceCode":"    Theorem:\n    a has a multiplicative inverse modulo n iff gcd(a,n) = 1\n\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)","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/modular_division.py#L14-L50","documentation":"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.","triggerScenarios":"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.","commonSituations":"Passing a modulus from unvalidated user input, misreading the argument order (n where a is expected), or test code that exercises edge moduli.","solutions":["Supply n >= 2, e.g. modular_division(4, 8, 5).","Check the parameter order: the signature is (a, b, n) with n last.","Validate modulus at input: if n < 2: reject with your own error before calling."],"exampleFix":"# before\nmodular_division(4, 8, 1)\n\n# after\nmodular_division(4, 8, 5)","handlingStrategy":"validation","validationCode":"if n < 2:\n    raise ValueError('modulus must be an integer >= 2')","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Pass the modulus as a keyword: modular_division(a, b, n=n).","Validate moduli at configuration time in crypto/number-theory code."],"tags":["math","number-theory","valueerror","modular-arithmetic"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}