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.
|
||||
* Uses the Extended Euclidean Algorithm.
|
||||
*
|
||||
* @author Matt C [matt@artemisbot.uk]
|
||||
* @param {number} x
|
||||
* @param {number} y
|
||||
* @returns {number}
|
||||
* @author Barry B [profbbrown@gmail.com]
|
||||
* @param {number} a
|
||||
* @param {number} n
|
||||
* @returns {number|null}
|
||||
*/
|
||||
static modInv(x, y) {
|
||||
x %= y;
|
||||
for (let i = 1; i < y; i++) {
|
||||
if ((x * i) % y === 1) {
|
||||
return i;
|
||||
}
|
||||
static modInv(a, n) {
|
||||
let t = 0, newT = 1, r = n, newR = a;
|
||||
|
||||
while (newR !== 0) {
|
||||
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