finding Inverse Modulo of a range of numbers under modulo m

While searching about inverse modulo, i got to know about a concise algorithm to find inverse modulo of
numbers in range[1…n) under modulo m.

Time complexity of this approach is O(n).

Implementation of the algorithm:

r[1] = 1;
for (int i=2; i<n; ++i)
r[i] = (m - (m/i) * r[m%i] m) m;

Here is the link:
http://e-maxx.ru/algo/reverse_element

I am unable to understand the proof of the algorithm.
It would be very helpful if anyone explains the same in a simple way.

i DOnt Know!

When you muliply r[i] on the left hand and right hand side.

r[i] * i = 1 mod m

(m mod i ) * r[i]= - (m/i)

Now multiply r[m%i].

Thus r[m%i]*(m%i)=1

r[i] * 1= -(m/i)*r[m%i] mod m

r[i]=(m-(m/i)*r[m%i])%m

alt text

Hope this helps.
Sorry I dont know how to use latex. :frowning:

1 Like

This was indeed helpful.
I did not realise r[i]*i=1 mod m and so the confusion arose.