147 lines
2.9 KiB
JavaScript
147 lines
2.9 KiB
JavaScript
function abs(a) {
|
|
return (a >= 0) ? a : -a;
|
|
}
|
|
|
|
function bitLength(a) {
|
|
if (typeof a === 'number')
|
|
a = BigInt(a);
|
|
if (a === 1n) {
|
|
return 1;
|
|
}
|
|
let bits = 1;
|
|
do {
|
|
bits++;
|
|
} while ((a >>= 1n) > 1n);
|
|
return bits;
|
|
}
|
|
|
|
function eGcd(a, b) {
|
|
if (typeof a === 'number')
|
|
a = BigInt(a);
|
|
if (typeof b === 'number')
|
|
b = BigInt(b);
|
|
if (a <= 0n || b <= 0n)
|
|
throw new RangeError('a and b MUST be > 0');
|
|
let x = 0n;
|
|
let y = 1n;
|
|
let u = 1n;
|
|
let v = 0n;
|
|
while (a !== 0n) {
|
|
const q = b / a;
|
|
const r = b % a;
|
|
const m = x - (u * q);
|
|
const n = y - (v * q);
|
|
b = a;
|
|
a = r;
|
|
x = u;
|
|
y = v;
|
|
u = m;
|
|
v = n;
|
|
}
|
|
return {
|
|
g: b,
|
|
x,
|
|
y
|
|
};
|
|
}
|
|
|
|
function gcd(a, b) {
|
|
let aAbs = (typeof a === 'number') ? BigInt(abs(a)) : abs(a);
|
|
let bAbs = (typeof b === 'number') ? BigInt(abs(b)) : abs(b);
|
|
if (aAbs === 0n) {
|
|
return bAbs;
|
|
}
|
|
else if (bAbs === 0n) {
|
|
return aAbs;
|
|
}
|
|
let shift = 0n;
|
|
while (((aAbs | bAbs) & 1n) === 0n) {
|
|
aAbs >>= 1n;
|
|
bAbs >>= 1n;
|
|
shift++;
|
|
}
|
|
while ((aAbs & 1n) === 0n)
|
|
aAbs >>= 1n;
|
|
do {
|
|
while ((bAbs & 1n) === 0n)
|
|
bAbs >>= 1n;
|
|
if (aAbs > bAbs) {
|
|
const x = aAbs;
|
|
aAbs = bAbs;
|
|
bAbs = x;
|
|
}
|
|
bAbs -= aAbs;
|
|
} while (bAbs !== 0n);
|
|
return aAbs << shift;
|
|
}
|
|
|
|
function lcm(a, b) {
|
|
if (typeof a === 'number')
|
|
a = BigInt(a);
|
|
if (typeof b === 'number')
|
|
b = BigInt(b);
|
|
if (a === 0n && b === 0n)
|
|
return BigInt(0);
|
|
return abs((a / gcd(a, b)) * b);
|
|
}
|
|
|
|
function max(a, b) {
|
|
return (a >= b) ? a : b;
|
|
}
|
|
|
|
function min(a, b) {
|
|
return (a >= b) ? b : a;
|
|
}
|
|
|
|
function toZn(a, n) {
|
|
if (typeof a === 'number')
|
|
a = BigInt(a);
|
|
if (typeof n === 'number')
|
|
n = BigInt(n);
|
|
if (n <= 0n) {
|
|
throw new RangeError('n must be > 0');
|
|
}
|
|
const aZn = a % n;
|
|
return (aZn < 0n) ? aZn + n : aZn;
|
|
}
|
|
|
|
function modInv(a, n) {
|
|
const egcd = eGcd(toZn(a, n), n);
|
|
if (egcd.g !== 1n) {
|
|
throw new RangeError(`${a.toString()} does not have inverse modulo ${n.toString()}`);
|
|
}
|
|
else {
|
|
return toZn(egcd.x, n);
|
|
}
|
|
}
|
|
|
|
function modPow(b, e, n) {
|
|
if (typeof b === 'number')
|
|
b = BigInt(b);
|
|
if (typeof e === 'number')
|
|
e = BigInt(e);
|
|
if (typeof n === 'number')
|
|
n = BigInt(n);
|
|
if (n <= 0n) {
|
|
throw new RangeError('n must be > 0');
|
|
}
|
|
else if (n === 1n) {
|
|
return 0n;
|
|
}
|
|
b = toZn(b, n);
|
|
if (e < 0n) {
|
|
return modInv(modPow(b, abs(e), n), n);
|
|
}
|
|
let r = 1n;
|
|
while (e > 0) {
|
|
if ((e % 2n) === 1n) {
|
|
r = r * b % n;
|
|
}
|
|
e = e / 2n;
|
|
b = b ** 2n % n;
|
|
}
|
|
return r;
|
|
}
|
|
|
|
export { abs, bitLength, eGcd, gcd, lcm, max, min, modInv, modPow, toZn };
|