Functional Weave
Code in Rust

math.gcd-lcm@2.0.0

impl/typescript/gcd.ts

961 bytes · the TypeScript implementation · view raw

function checkSafe(name: string, value: number): void {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer, received ${value}`);
  }
  if (!Number.isSafeInteger(value)) {
    throw new 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.
 */
export function 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. */
export function gcd(a: number, b: number): number {
  checkSafe("a", a);
  checkSafe("b", b);
  return Number(gcdWide(BigInt(a), BigInt(b)));
}