Functional Weave
Code in Rust

math.integer-sqrt@1.0.0

README.md

1,110 bytes · view raw

# math.integer-sqrt

The integer square root of `n`: the largest whole number `r` with `r * r <= n`,
so `integerSqrt(24)` is 4 and `integerSqrt(25)` is 5.

It exists so that capabilities which need a square root of a whole number
(economic order quantity, grid layouts) get the same answer in every language
without going through floating point. `Math.floor(Math.sqrt(n))` is right for
small numbers, but the double nearest to `n` is not `n` above 2^53 and the
square root of a number just below a perfect square can round up to it, so
each language here corrects the floating-point guess with exact integer
arithmetic (TypeScript `bigint`, Python `math.isqrt`, Rust `i128`).

Inputs are limited to 0 .. 2^53 - 1, the range where a JavaScript number is
still an exact integer, so the three languages agree on every answer. A
negative or fractional input, or one beyond that range, is an error.

To round a square root of a fraction `p / q` rather than truncate it, note
that `floor(sqrt(p / q)) = integerSqrt(floor(p / q))`: the floor of a square
root only changes at whole numbers. `inventory.eoq` uses this.