Skip to content

Instantly share code, notes, and snippets.

@rsha256
Last active March 10, 2021 18:59
Show Gist options
  • Save rsha256/21e5f5611d19ea27bbf6011b44e287b4 to your computer and use it in GitHub Desktop.
Save rsha256/21e5f5611d19ea27bbf6011b44e287b4 to your computer and use it in GitHub Desktop.
Tool for finding modular inverses for me to make CS70 questions πŸ˜„
class rs():
def __init__(self, p):
self.p = p # set the Galois Field
def divide(self, a, b):
a %= self.p
b %= self.p
b_mod_inv = 0 if b % self.p == 0 else self.find_mod_inv(b)
return (a*b_mod_inv) % self.p
def find_mod_inv(self, x):
p = self.p
x %= p
for i in range(1, p):
if 1 == ((x*i) % p):
return i
raise InverseNotFoundException("Could not find inverse for " + str(x) + " in moduli " + str(p))
class InverseNotFoundException(Exception):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment