Created
October 27, 2013 18:14
-
-
Save schie/7185944 to your computer and use it in GitHub Desktop.
This python script finds the multiplicative inverse of X mod Y
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
from sys import stdout | |
rs = [] | |
qs = [' ',' '] | |
xs = [1,0] | |
ys = [0,1] | |
def gcd(a, b): | |
if(len(rs) is 0): | |
rs.append(a) | |
if(b > 0): | |
rs.append(b) | |
r = a % b | |
q = int((a - r) / b) | |
qs.append(q) | |
x = xs[-2] - xs[-1] * q | |
xs.append(x) | |
y = ys[-2] - ys[-1] * q | |
ys.append(y) | |
gcd(b, r) | |
def print_it(): | |
for x in range(len(rs)): | |
stdout.write(str(rs[x]) + "\t" + str(qs[x]) + "\t" + str(xs[x]) + "\t" + str(ys[x]) + "\n") | |
temp = rs[0] * xs[-2] + rs[1] * ys[-2] | |
stdout.write("\n") | |
stdout.write(str(rs[0]) + " * " + str(xs[-2]) + " + " + str(rs[1]) + " * " + str(ys[-2]) + " = " + str(temp)) | |
stdout.write("\n") | |
if(1 is (rs[1] * ys[-2]) % rs[0]): | |
stdout.write('1 ≣ (' + str(rs[1]) + " * " + str(ys[-2]) + ') mod ' + str(rs[0])) | |
stdout.write("\nmultiplicative inverse of " + str(rs[1]) + " is " + str(ys[-2])) | |
else: | |
print("error") | |
stdout.write("\n") | |
def reset(): | |
rs[:] = [] | |
qs[:] = [' ',' '] | |
xs[:] = [1,0] | |
ys[:] = [0,1] | |
print("="*30) | |
gcd(4321, 2410) | |
print_it() | |
reset() | |
gcd(1769, 550) | |
print_it() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment