Last active
March 3, 2019 06:15
-
-
Save Jun-Wang-2018/b4eb2aaa59af3fbdf1ae1f7ab979b6ae to your computer and use it in GitHub Desktop.
Calculate modular inverse
This file contains 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
# Note: A and P must share no factor greater than 1. | |
def modular_inverse(A,P): | |
p0, a0 = 1, 0 | |
p1, a1 = 0, 1 | |
R0, R1 = P, A%P | |
while R1 != 1 and R1 != 0: | |
n, R2 = divmod(R0, R1) | |
p2 = p0 - n*p1 ; a2 = a0 - n*a1 | |
p0 = p1; a0 = a1; p1 = p2; a1 = a2 | |
R0 = R1; R1 = R2 | |
if R1 == 0: | |
# return "Error: A and P share factor "+ str(R0) + ". They must share no factor greater than 1." | |
return a1 % P |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment