Fastest modular exponentiation in JavaScript

后端 未结 4 1629
余生分开走
余生分开走 2021-02-01 09:38

My problem is to compute (g^x) mod p quickly in JavaScript, where ^ is exponentiation, mod is the modulo operation. All inputs are nonnega

4条回答
  •  名媛妹妹
    2021-02-01 10:11

    I use "%" for modular (mod) and "/" for integer division. Let function f(p,g,x,r) calculate (r*g^x)%p on the condition that r

    bigint_t f(p,g,x,r) {
      bigint_t i, z = g, y;
      for (i = 1; i < x; ++i) {
        y = z; z *= g;
        if (z > p) break;
      }
      if (i >= x - 1) return r*z%p; // g^x*r%p = g^x*r
      else return f(p,y,x/i,g^(x%i)*r%p); // reduce to (r*g^(x%i)%p)*(g^i)^(x/i)%p
    }
    

    This routine involves a little more calculation, but each integer is less than 4096 bits which is usually much smaller than g^x. I believe this could be more efficient than the direct calculation. Also note that g^(x%i) can be calculated in a faster manner because we have calculated g^(i+1).

    EDIT: see this post. Mehrdad gives the right (and better) solution.

提交回复
热议问题