Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Comment thread
clockgrove-pendulum[bot] marked this conversation as resolved.
Resolved
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
```
10 changes: 10 additions & 0 deletions src/math.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
13 changes: 12 additions & 1 deletion test/math.test.mjs
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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);
});
Loading