Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ssanin82
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssanin82/0b55a730ddbc7dafa94d to your computer and use it in GitHub Desktop.
Save ssanin82/0b55a730ddbc7dafa94d to your computer and use it in GitHub Desktop.
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