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

后端 未结 2 1414
挽巷
挽巷 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;
    }
    

提交回复
热议问题