Functional Weave
Code in TypeScript

math.gcd-lcm@2.0.0

impl/typescript/lcm.ts

518 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { gcd } from "./math_gcd_lcm_gcd.ts";  ← gcd, another function of this group · built into the same file, even by a slim install

/** Least common multiple, never negative; 0 when either input is 0. */
export function lcm(a: number, b: number): number {
  const g = gcd(a, b);
  if (g === 0) return 0;
  // Divide before multiplying: a * b overflows long before the lcm does.
  const result = (BigInt(Math.abs(a)) / BigInt(g)) * BigInt(Math.abs(b));
  if (result > BigInt(Number.MAX_SAFE_INTEGER)) {
    throw new RangeError(`the lcm of ${a} and ${b} exceeds 2^53 - 1`);
  }
  return Number(result);
}