简体   繁体   中英

Calculate (a^b)%c where 0<=a,b,c<=10^18

How can I calculate (a ^ b) % c , where 0 <= a, b, c <= 10^18 . Here, (a ^ b) means a to the power b , not a xor b .

My current code for the problem is:

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 long long temp = bigMod(b, p / 2ll, m);
        return ((temp) * (temp) )% m;
    }else return (b  *  bigMod(b, p-1, m)) % m;
}

For this input:

a = 12345 b = 123456789 and c = 123456789012345

the expected output should be:

59212459031520

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM