Skip to content

Instantly share code, notes, and snippets.

@Hemie143
Created November 15, 2017 23:05
Show Gist options
  • Select an option

  • Save Hemie143/dd5a3ae8afbdbf1948d5a8ee1ff7e47b to your computer and use it in GitHub Desktop.

Select an option

Save Hemie143/dd5a3ae8afbdbf1948d5a8ee1ff7e47b to your computer and use it in GitHub Desktop.
Modulo and inverse
def power(x, y, p):
res = 1
x = x % p
while y > 0:
if y & 1:
res = (res * x) % p
y = y//2
x = (x * x) % p
return res
def modInverse(a, p):
# Only if p is prime
return power(a, p - 2, p)
def modFact(n, p):
if p <= n:
return 0
res = p-1
for i in range(n+1, p):
res = (res * modInverse(i, p)) % p
return res
n = 21
p = 23
print('{}! mod {} = {}'.format(n, p, modFact(n, p)))
print('inverse({}, {}) = {}'.format(22, 23, modInverse(22, 23)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment