Barrett.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // BarrettMu, a class for performing Barrett modular reduction computations in
  2. // JavaScript.
  3. //
  4. // Requires BigInt.js.
  5. //
  6. // Copyright 2004-2005 David Shapiro.
  7. //
  8. // You may use, re-use, abuse, copy, and modify this code to your liking, but
  9. // please keep this header.
  10. //
  11. // Thanks!
  12. //
  13. // Dave Shapiro
  14. // dave@ohdave.com
  15. function BarrettMu(m)
  16. {
  17. this.modulus = biCopy(m);
  18. this.k = biHighIndex(this.modulus) + 1;
  19. var b2k = new BigInt();
  20. b2k.digits[2 * this.k] = 1; // b2k = b^(2k)
  21. this.mu = biDivide(b2k, this.modulus);
  22. this.bkplus1 = new BigInt();
  23. this.bkplus1.digits[this.k + 1] = 1; // bkplus1 = b^(k+1)
  24. this.modulo = BarrettMu_modulo;
  25. this.multiplyMod = BarrettMu_multiplyMod;
  26. this.powMod = BarrettMu_powMod;
  27. }
  28. function BarrettMu_modulo(x)
  29. {
  30. var q1 = biDivideByRadixPower(x, this.k - 1);
  31. var q2 = biMultiply(q1, this.mu);
  32. var q3 = biDivideByRadixPower(q2, this.k + 1);
  33. var r1 = biModuloByRadixPower(x, this.k + 1);
  34. var r2term = biMultiply(q3, this.modulus);
  35. var r2 = biModuloByRadixPower(r2term, this.k + 1);
  36. var r = biSubtract(r1, r2);
  37. if (r.isNeg) {
  38. r = biAdd(r, this.bkplus1);
  39. }
  40. var rgtem = biCompare(r, this.modulus) >= 0;
  41. while (rgtem) {
  42. r = biSubtract(r, this.modulus);
  43. rgtem = biCompare(r, this.modulus) >= 0;
  44. }
  45. return r;
  46. }
  47. function BarrettMu_multiplyMod(x, y)
  48. {
  49. /*
  50. x = this.modulo(x);
  51. y = this.modulo(y);
  52. */
  53. var xy = biMultiply(x, y);
  54. return this.modulo(xy);
  55. }
  56. function BarrettMu_powMod(x, y)
  57. {
  58. var result = new BigInt();
  59. result.digits[0] = 1;
  60. var a = x;
  61. var k = y;
  62. while (true) {
  63. if ((k.digits[0] & 1) != 0) result = this.multiplyMod(result, a);
  64. k = biShiftRight(k, 1);
  65. if (k.digits[0] == 0 && biHighIndex(k) == 0) break;
  66. a = this.multiplyMod(a, a);
  67. }
  68. return result;
  69. }