Hi,
I am unable to understand the iterative version of fast modular exponentiation code.
long long prod(long long a, long long b, long long mod = MOD)
{
long long res = 0;
while(b)
{
if(b & 1)
res = (res + a) % mod;
a = (a + a) % mod;
b >>= 1;
}
return res;
}
long long bpow(long long a, long long b, long long mod = MOD)
{
long long res = 1;
while(b)
{
if(b & 1)
res = prod(res, a, mod);
a = prod(a, a, mod);
b >>= 1;
}
return res;
}
The prod function does overflow safe multiplication, again similar to fast exponentiation code, but hard to get.