isqrt function

int isqrt(
  1. int n
)

Returns the integer square root of n (the floor of its real square root).

Returns 0 for any n less than or equal to zero. Exact for every positive int on native platforms, including the 64-bit maximum. On the web, int is a JavaScript number, so exactness holds only up to 2^53.

Example:

isqrt(17); // 4
isqrt(16); // 4

Audited: 2026-06-12 11:26 EDT

Implementation

int isqrt(int n) {
  if (n <= 0) return 0;
  int x = n;
  // First Newton step is ceil(n / 2). Written as a subtraction because
  // (n + 1) wraps negative at the 64-bit maximum, and with ~/ because >>
  // truncates to 32 bits on the web.
  int y = n - n ~/ 2;
  // Newton iteration decreases monotonically until it reaches floor(sqrt(n)).
  while (y < x) {
    x = y;
    // ~/ 2 rather than >> 1 so values above 2^32 stay correct on the web.
    y = (x + n ~/ x) ~/ 2;
  }
  return x;
}