How to calculate power?

Help Please,

Can anybody can tell me how to calculate 21000000000 fast enough in c++.

1 Like

You can use modular exponentiation to calculate powers of 64-bit integers modulo some integer.
Below is a function to calculate a^{b}%c.

long long powerMod(long long a, long long b, long long c)
{
    long long result = 1;
    long long temp = 1;
    long long mask = 1;
    for (int i = 0; i < 64; i++)
    {
        mask = (i == 0) ? 1 : (mask * 2);
        temp = (i == 0) ? (a % c) : (temp * temp) % c;
        
        if ((b & mask) == mask)
          result = (result * temp) % c;
   }
   return result;
}
1 Like