961 bytes · the TypeScript implementation · view raw
function checkSafe(name: string, value: number): void {
if (!Number.isInteger(value)) {
thrownew TypeError(`${name} must be an integer, received ${value}`);
}
if (!Number.isSafeInteger(value)) {
thrownew RangeError(`${name} is outside the safe integer range (±9007199254740991)`);
}
}
/** * Euclid's algorithm on wide integers, with no range limit. Never negative; * gcdWide(0, 0) is 0. Exported for fraction arithmetic (math.rational), which * reduces products that are already past 2^53 before it checks them. */exportfunction gcdWide(a: bigint, b: bigint): bigint {
let x = a < 0n ? -a : a;
let y = b < 0n ? -b : b;
while (y !== 0n) {
const r = x % y;
x = y;
y = r;
}
return x;
}
/** Greatest common divisor, never negative; gcd(0, n) is |n| and gcd(0, 0) is 0. */exportfunction gcd(a: number, b: number): number {
checkSafe("a", a);
checkSafe("b", b);
return Number(gcdWide(BigInt(a), BigInt(b)));
}