1

Was suggested to ask this question here.

I'm having a difficult time understanding the Modular Multiplicative Inverse. I'm new to Python and found an example (below) of finding the Mod Inverse and I'd like a better picture (or understanding) of what's happening here to help me further comprehend this.

Why would finding the %(remainders) be useful to find the inverse? After my research, my understanding is finding what I can multiply x by to get (mod m)? (examples below) Why is finding the remainder needed?

I've added a few things below:

(1) I use PythonTutor (screen shot below) which help me get a visual on what exactly is happening step by step. Any further explanation on what's happening in the IF statement would be helpful.

(2) And a example I jotted down on paper to further show how the Inverse is found. I'm including this to show why I don't understand a remainder is needed.

Example:

def modInv(a, m):
for x in range(1, m):
    if (((a%m) * (x%m)) % m == 1):
        return x
return -1


a = 3 m = 11

print(modInv(a, m))

Output: 4

In PythonTuter, I see the program going through the range to see if the condition is true/false, if true, return x. IF Statement finds the remainder of a%m and multiplies it by the remainder of x%m. Then use that number to find the remainder of m. Why the need to find all these remainders?

PythonTutor screen shot here

Below Image: So, for this example Inverse of 5 mod 7. I'm able find the inverse pretty quickly in this problem w/o the need for remainders...

Hand written Mod problem here

Ultimately, I'm really trying to wrap around why remainders are needed in a function above to find the inverse. Any help understanding this would be appreciated.

Bill Dubuque
  • 282,220
  • 2
    From a mathematical perspective one finds an inverse by performing an extended Euclidean algorithm to express the GCD of two positive integers as the difference of some multiples of them. The remainders are an ingredient of the division algorithm which is repeated until a zero remainder is reached, at which point you've found the GCD. – hardmath Sep 02 '21 at 01:36
  • 3
    They are not neccessary. x%m = x by 1 < x < m so that remainder is not needed, and as an optimization a%m can be computed once before the loop (since the input a might be huge). But much more efficient than this brute force search is to use the extended Euclidean algorithm as described here. – Bill Dubuque Sep 02 '21 at 08:25
  • 1
    Further optimization on the given code would not only include @Bill Dubuque's optimization, but noting that unless the remainder of $a$ times $x$ is greater than $m$ the remainder of $ax$ modulo $m$ can't be one. Parity also plays a role,but helps less. – Roddy MacPhee Sep 03 '21 at 00:25

0 Answers0