I have a problem with my binary powering function. Variable which contains the result overflows while performing multiplication and gives me a wrong result. It happens when the source value is greater than 4,312,952,827. So how do I solve this problem? Here's the code of my function.
unsigned long long binpow(unsigned long long a, unsigned long long n, unsigned long long m)
{
unsigned long long res;
res=1;
while (n)
{
if (n & 1)
{
res=(res*a)%m;
n--;
}
a=(a*a)%m;
n >>= 1;
}
return res;
}