mirror of
https://github.com/gchq/CyberChef.git
synced 2025-04-21 23:36:16 -04:00
modInv uses Extended Euclidean Algorithm
This commit is contained in:
parent
9c696b523d
commit
8530c47cb8
1 changed files with 17 additions and 10 deletions
|
@ -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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue