Fastest modular exponentiation in JavaScript

后端 未结 4 1569
余生分开走
余生分开走 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<p and g<p. f() can be implemented as:

    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.

    0 讨论(0)
  • 2021-02-01 10:16

    Would some other client side technology that's callable from JS, such as a Java applet or Flash movie, be acceptable? BigInt's approach is already fairly fast. You can tweak BigInt, or you can try a different algorithm, but you probably won't get an order of magnitude improvement.

    0 讨论(0)
  • 2021-02-01 10:22

    Try this Montgomery modular reduction from http://code.google.com/p/bi2php/ on JavaScript.

    0 讨论(0)
  • 2021-02-01 10:32

    Why not do it server side in some kind of web service using a more appropriate language like C? Times will then be time for one round trip (less than 9 seconds), plus the time for the server to calculate the result using some BigInt library in native code. This is likely to be much faster.

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