Skip to content

Instantly share code, notes, and snippets.

@miyaokamarina
Last active July 11, 2023 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miyaokamarina/e5be389d8e6975ce0a0969f3161acc1c to your computer and use it in GitHub Desktop.
Save miyaokamarina/e5be389d8e6975ce0a0969f3161acc1c to your computer and use it in GitHub Desktop.
Modular multiplicative inverse (mod 2^w) in JavaScript
/**
* Modular multiplicative inverse (mod 2^w).
*
* Find x, s.t.
*
* ax ≡ 1 (mod 2^w)
*
* Based on Hurchalla, J. (2022). “An Improved Integer Modular Multiplicative
* Inverse (modulo 2^w)”. https://arxiv.org/abs/2204.04342
*
* @param {number | bigint} a A positive odd integer to invert.
* @param {number} w Bit width.
*/
export const inv = (a, w = 32) => {
let u = x => BigInt.asUintN(w, x)
a = u(BigInt(a));
let x = u(3n * a) ^ 2n;
let y = u(1n - u(a * x));
let n = (w >> 2) - 1;
while (n) {
x = u(x * u(1n + y));
y = u(y * y);
n = n >> 1;
}
return x;
};
if (inv(105n, 8) !== 217n) throw new Error('8-bit test failed.');
if (inv(217n, 8) !== 105n) throw new Error('8-bit test failed.');
if (inv(62169n, 16) !== 28009n) throw new Error('16-bit test failed.');
if (inv(28009n, 16) !== 62169n) throw new Error('16-bit test failed.');
if (inv(277803737n, 32) !== 2897767785n) throw new Error('32-bit test failed.');
if (inv(2897767785n, 32) !== 277803737n) throw new Error('32-bit test failed.');
if (inv(12605985483714917081n, 64) !== 15009553638781119849n) throw new Error('64-bit test failed.');
if (inv(15009553638781119849n, 64) !== 12605985483714917081n) throw new Error('64-bit test failed.');
if (inv(327738287884841127335028083622016905945n, 128) !== 266050134430354249485913702517209329001n) throw new Error('128-bit test failed.');
if (inv(266050134430354249485913702517209329001n, 128) !== 327738287884841127335028083622016905945n) throw new Error('128-bit test failed.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment