Last active
August 29, 2015 14:11
-
-
Save ssanin82/0b55a730ddbc7dafa94d to your computer and use it in GitHub Desktop.
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 extended_gcd(aa, bb): | |
lastremainder, remainder = abs(aa), abs(bb) | |
x, lastx, y, lasty = 0, 1, 1, 0 | |
while remainder: | |
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) | |
x, lastx = lastx - quotient * x, x | |
y, lasty = lasty - quotient * y, y | |
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) | |
def modinv(a, m): | |
g, x, y = extended_gcd(a, m) | |
if g != 1: | |
raise ValueError | |
return x % m | |
# ----------------------- | |
def modinv2(a, m): | |
orgm = m | |
x, lastx, y, lasty = 0, 1, 1, 0 | |
while m: | |
a, (quotient, m) = m, divmod(a, m) | |
x, lastx = lastx - quotient * x, x | |
y, lasty = lasty - quotient * y, y | |
if a != 1: | |
raise ValueError | |
return lastx % orgm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment