diff --git a/README.md b/README.md index c9257d2..dc30865 100644 --- a/README.md +++ b/README.md @@ -122,3 +122,10 @@ It also exports `gcd(a, b)`, which returns the greatest common divisor of the in import { gcd } from "./src/math.mjs"; gcd(12, 18); // 6 ``` + +It also exports `lcm(a, b)`, which returns the least common multiple of the integers `a` and `b` as a non-negative number. The sign of either argument does not matter, and it returns `0` when either argument is `0`. It throws a `RangeError` when `a` or `b` is not an integer. + +```js +import { lcm } from "./src/math.mjs"; +lcm(4, 6); // 12 +``` diff --git a/src/math.mjs b/src/math.mjs index 76872d7..0be0646 100644 --- a/src/math.mjs +++ b/src/math.mjs @@ -124,3 +124,13 @@ export function gcd(a, b) { } return a; } + +export function lcm(a, b) { + if (!Number.isInteger(a) || !Number.isInteger(b)) { + throw new RangeError("lcm: a and b must be integers"); + } + if (a === 0 || b === 0) { + return 0; + } + return Math.abs((a / gcd(a, b)) * b); +} diff --git a/test/math.test.mjs b/test/math.test.mjs index 0ab1ea1..3d730d1 100644 --- a/test/math.test.mjs +++ b/test/math.test.mjs @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { abs, add, clamp, cube, factorial, gcd, isEven, lerp, max, mean, median, min, multiply, product, sign, square, subtract, sum } from "../src/math.mjs"; +import { abs, add, clamp, cube, factorial, gcd, isEven, lcm, lerp, max, mean, median, min, multiply, product, sign, square, subtract, sum } from "../src/math.mjs"; test("add", () => { assert.equal(add(2, 3), 5); @@ -136,3 +136,14 @@ test("gcd", () => { assert.equal(gcd(-12, 18), 6); assert.equal(gcd(0, 0), 0); }); + +test("lcm", () => { + assert.equal(lcm(4, 6), 12); + assert.equal(lcm(-4, 6), 12); + assert.equal(lcm(4, -6), 12); + assert.equal(lcm(0, 5), 0); + assert.equal(lcm(5, 0), 0); + assert.equal(lcm(7, 1), 7); + assert.throws(() => lcm(2.5, 4), RangeError); + assert.throws(() => lcm(4, 2.5), RangeError); +});