Hi, If i want to compute (1065*1001) mod 1000 , the best way to do this is computing (1065 modulo 1000) and (1001 modulo 1000) then Multiplying the two numbers so (1065 modulo 1000) = 65 and (1001 modulo 1000) = 1 then 65 * 1 = 65 so: (1065*1001) mod 1000 = 65 this way is much easier than computing 1065*1001 then modulo 1000
so my question is: is there a way resemble to the way above working with division like (6072/1012) mod 5 thanks.
There is a way when modulo is a prime number.
Using Fermat's little theorem we have:
a ^ p ≡ a (mod p), p is prime
=>
a ^ ( p — 2 ) ≡ 1 / a (mod p)
So we have ( a / b ) % m = ( a % m ) * ( ( 1 / b ) % m ) = ( a % m ) * ( ( b ^ ( m — 2 ) ) % m )
Thank you but this is not helping, because b ^ ( m — 2 ) is a huge number when m is big, and I want to make calculation easier not harder. any better ideas??
Calculate it by modulo m.
(a * b) mod m == ((a mod m) * (b mod m)) mod m
this is also useless when m is big for example m=10000000007 (10^9+7) so i have to multiply (b mod m)*(b mod m)*(b mod m) ......(b mod m)*(b mod m) (m times)
yes I know , the main problem is that the complexity of computing (a/b) mod m is O(m) and if I have n calculations to do so the total complexity is O(nm) which is slow.
so I need way to calculate each ( (a/b) mod m ) in O(1) time
Only O(log(m)) is possible. And only if gcd(b,m)==1. Google 'fast exponentiation'