Calculation (Pow(a,b) mod (c) at large a,b,c



  • How to calculate this expression without saying the filling Pow ?

    ulong Pow(ulong a, ulong b)
    {
      ulong p = 1;
      for (ulong i = 0; i < b; ++i)
        p *= a;
      return p;
    }
    

    ulong m = Pow(a, b) % c;



  • If a * c Don't get out of here. ulongSo...

    ulong Pow(ulong a, ulong b)
    {
      a = a % c;
      ulong p = 1;
      for (ulong i = 0; i < b; ++i)
        p = (p * a) % c;
      return p;
    }
    

    Invitation: p < c♪ Multiplying p * a < c * aand there is no overcrowding.


    Updating: For larger values, it makes sense to multiply by sequential formation into squares.

    ulong Pow(ulong a, ulong b)
    {
      a = a % c;
      ulong p = 1;
      ulong r = 1;
      while (b > 0)
      {
        if (b % 2 != 0)
          r = (r * p) % c;
        b = b / 2;
        p = (p * a) % c;
      }
      return r;
    }
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2