Functional Weave
Code in Rust

math.gcd-lcm@1.0.0

README.md

1,073 bytes · view raw

# math.gcd-lcm

Returns the greatest common divisor (also called the highest common factor)
and the least common multiple of two integers. Both are never negative:
`gcd(-4, 6)` is 2 and `lcm(-4, 6)` is 12.

The conventions at zero are the ones every maths library uses: `gcd(0, n)` is
`|n|`, `gcd(0, 0)` is 0, and the lcm of anything with 0 is 0.

The lcm is computed as `|a| / gcd * |b|`, dividing first. The textbook
`a * b / gcd` overflows a 64-bit integer, and loses digits in a JavaScript
number, long before the answer itself is large; one of the vectors is a case
where it does.

Inputs and results are limited to ±(2^53 - 1), the range where a JavaScript
number is still an exact integer, so the three languages agree on every
answer. An input outside it, or an lcm beyond it, is an error.

Also exported, for capabilities that build on this one: `gcd(a, b)`,
`lcm(a, b)`, and `gcdWide`, a gcd over wide integers (TypeScript `bigint`,
Python `int`, Rust `i128`) with no range limit, used by `math.rational` to
reduce intermediate products before they are checked.