Thanks to it, I managed to understand a bit better the usage and concept of modular multiplicative inverse.
Namely, if we want to compute x^(-1) % (M=a big prime number) then we can use Euler’s Theorem and do:
x^(M-2) % M and compute it by fast exponentiantion, is this so?
However, many contestants there used this function:
long long int big_mod(long long int i, long long int j)
{
if(j==0)
return 1;
long long int x=big_mod(i,j>>1);
x=(x*x)%mod;
if(j&1)
return (x*i)%mod;
return x;
}
My doubt is:
Is this function doing the same job as the standard fast exponentiation function? If not, why?
The function calculates (a^b)%mod, because (a^b)mod = ((a^(b/2)) * (a^(b/2)) mod) if exponent b is even number,
else if b is odd, (a^b)%mod = ((a^[b/2])%mod)((a^[b/2])%mod)(a%mod) ([x] is floor function)
That the function can calculate (a^b)%mod like this way is based on the fact (a*b)mod = ((a mod) * (b%mod))%mod.
By the way, if we use extended euclid algorithm, we can also calculate multiplicative inverse faster.
If a is inverse of x, then ax = 1 (mod N), that means ax-Ny=1. in this problem N(1000000007) is a prime number, the equation ax-Ny=1 has always a solution.
def ext_gcd(a, b):
if b==0:
return (1, 0)
else:
x, y = ext_gcd(b, a%b)
return (y, x-(a/b)*y)
def mod_inv(a,N):
x, y = ext_gcd(a, N)
if x < 0:
return (x+N)%N
The function calculates (a^b) mod M in O(logb). if “standard fast exponentiation function” points to the function which calculates a^b in log time, the function and the standard function do the same job