How can I calculate (a ^ b) % c
, where 0 <= a, b, c <= 10^18
.
Here, (a ^ b)
means a
to the power b
, not
You have a problem with temp*temp (long long overflow). You can omit this problem using algorithm of fast mod power to multiply them mod m. Here You have working code:
unsigned long long bigMultiply(unsigned long long b,unsigned long long p, unsigned long long m)
{
if(p == 0 )return b;
if(p%2 == 0)
{
unsigned long long temp = bigMultiply(b,p/2ll,m);
return ((temp)+(temp))%m;
}
else
return (b + bigMultiply(b,p-1,m))%m;
}
unsigned long long bigMod(unsigned long long b,unsigned long long p, unsigned long long m)
{
if(b == 1)
return b;
if(p == 0 )return 1;
if( p == 1)return b;
if(p%2 == 0)
{
unsigned ll temp = bigMod(b,p/2ll,m);
return bigMultiply(temp,temp,m);
}
else
return (b * bigMod(b,p-1,m))%m;
}
I use this code in c++:
long long power(long long a, long long b, long long c)
{
if (b==0)
{
return 1;
}
if (b % 2 == 0)
{
long long w = power(a, b/2, c);
return (w*w) % c;
}
else
{
int w = power(a, b-1, c);
return (a*w) % c;
}
}
It has logarithmic complexity.