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

后端 未结 2 1413
挽巷
挽巷 2021-01-22 15:30

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

相关标签:
2条回答
  • 2021-01-22 16:07

    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;
    }
    
    0 讨论(0)
  • 2021-01-22 16:11

    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.

    0 讨论(0)
提交回复
热议问题