Skip to content

Instantly share code, notes, and snippets.

@yarjor
Created March 30, 2018 12:40
Show Gist options
  • Select an option

  • Save yarjor/86ed211a3686f34e29bd247813739d45 to your computer and use it in GitHub Desktop.

Select an option

Save yarjor/86ed211a3686f34e29bd247813739d45 to your computer and use it in GitHub Desktop.
[Modular Inverse] #crypto #math
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment