modInv uses Extended Euclidean Algorithm

This commit is contained in:
Barry Brown 2024-06-13 17:19:11 +00:00
parent 9c696b523d
commit 8530c47cb8

View file

@ -1266,19 +1266,26 @@ class Utils {
/** /**
* Finds the modular inverse of two values. * Finds the modular inverse of two values.
* Uses the Extended Euclidean Algorithm.
* *
* @author Matt C [matt@artemisbot.uk] * @author Barry B [profbbrown@gmail.com]
* @param {number} x * @param {number} a
* @param {number} y * @param {number} n
* @returns {number} * @returns {number|null}
*/ */
static modInv(x, y) { static modInv(a, n) {
x %= y; let t = 0, newT = 1, r = n, newR = a;
for (let i = 1; i < y; i++) {
if ((x * i) % y === 1) { while (newR !== 0) {
return i; const q = Math.floor(r / newR);
} [t, newT] = [newT, t - q * newT];
[r, newR] = [newR, r - q * newR];
} }
if (r > 1) return null;
if (t < 0) t = t + n;
return t;
} }