Created
November 15, 2017 23:05
-
-
Save Hemie143/dd5a3ae8afbdbf1948d5a8ee1ff7e47b to your computer and use it in GitHub Desktop.
Modulo and inverse
This file contains hidden or 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 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