612 bytes · the TypeScript implementation · view raw
/** * The largest whole number whose square does not exceed `n`. * * The floating-point square root is only a first guess: it is corrected with * exact bigint arithmetic, so a number just below a perfect square never rounds * up to its root. */exportfunction integerSqrt(n: number): number {
if (!Number.isSafeInteger(n) || n < 0) {
thrownew RangeError(`n must be a whole number from 0 to 2^53 - 1, received ${n}`);
}
const target = BigInt(n);
let r = BigInt(Math.floor(Math.sqrt(n)));
while (r * r > target) r -= 1n;
while ((r + 1n) * (r + 1n) <= target) r += 1n;
return Number(r);
}