Last active
August 4, 2021 08:11
-
-
Save paiv/a581f02200f3dcdf739ddd8d3b4cdfe6 to your computer and use it in GitHub Desktop.
modular multiplicative inverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def modinv(n, mod): | |
t, w, r = 0, 1, mod | |
while n: | |
(q, n), r = divmod(r, n), n | |
t, w = w, t - q * w | |
if r > 1: raise Exception('not invertible ' + repr(n)) | |
if t < 0: t += mod | |
return t |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python 3.8:
pow(n, -1, mod)