2023-03-03 17:34:15 +00:00
|
|
|
export function mod_exp(a, b, n) {
|
|
|
|
let res = 1n;
|
|
|
|
|
|
|
|
while (b > 0n) {
|
|
|
|
if (b % 2n === 1n) {
|
|
|
|
res = (res * a) % n;
|
|
|
|
}
|
|
|
|
|
|
|
|
b >>= 1n;
|
|
|
|
a = (a * a) % n;
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
2023-03-04 00:25:54 +00:00
|
|
|
|
|
|
|
export function mod_inv(a, n) {
|
|
|
|
let t = 0n;
|
|
|
|
let new_t = 1n;
|
|
|
|
let r = n;
|
|
|
|
let new_r = a;
|
|
|
|
|
|
|
|
while (new_r !== 0n) {
|
|
|
|
let quotient = r / new_r;
|
2023-03-04 10:50:49 +00:00
|
|
|
|
|
|
|
let t_temp = t;
|
2023-03-04 00:25:54 +00:00
|
|
|
t = new_t;
|
2023-03-04 10:50:49 +00:00
|
|
|
new_t = t_temp - quotient * new_t;
|
|
|
|
|
|
|
|
let r_temp = r;
|
2023-03-04 00:25:54 +00:00
|
|
|
r = new_r;
|
2023-03-04 10:50:49 +00:00
|
|
|
new_r = r_temp - quotient * new_r;
|
2023-03-04 00:25:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (t < 0) {
|
|
|
|
t = t + n;
|
|
|
|
}
|
|
|
|
|
|
|
|
return t;
|
|
|
|
}
|
2023-03-17 10:42:11 +00:00
|
|
|
|
2023-03-18 15:41:37 +00:00
|
|
|
export function gcd(a, b) {
|
|
|
|
// check a, b are correct types.
|
|
|
|
a *= 1n;
|
|
|
|
b *= 1n;
|
|
|
|
while (b !== 0n) {
|
|
|
|
let temp = b;
|
|
|
|
b = a % b;
|
|
|
|
a = temp;
|
|
|
|
}
|
|
|
|
return a;
|
|
|
|
}
|
|
|
|
|
2023-03-17 10:42:11 +00:00
|
|
|
window.mod_exp = mod_exp;
|
2023-03-18 15:41:37 +00:00
|
|
|
window.mod_inv = mod_inv;
|
|
|
|
window.gcd = gcd;
|