I am working on an algorithm that calculates the multiplicative inverse of a number. I had to make a function to do this. However, I am stuck on an optimization.
My algorithm works, but only for relatively small numbers.
Given 3 numbers (a,b,n)
, i need to return a/b (mod n)
.
This part I can do. However, when n
is really large, my code becomes impossibly slow because I am solving it this way:
for i in range(1,n):
if b*i%n == a%n:
return i
My problem with this is again the size of n
. If it gets huge, the code does not run.
Now, assuming my numbers are 3,2,7
, I need to obtain the answer 5
without checking all the numbers. So I tried using the extended Euclidean algorithm.
This is what I did:
ax + by = 1
ax = 1 (mod n) => ax - 1 = qn, where q is an integer
I end up with the equation:
ax - qn = 1
If I sum in my numbers, I end up with:
3x + 7q = 1
How can I solve this? Is there a better way?