Square Root (x) Visualization & Animation
Finds the integer floor of √n without built-in functions using binary search on the answer space.
## What is it?
Compute the integer square root of a non-negative integer `n` — the largest integer `x` such that `x² ≤ n` — without using any built-in square root function. Solved using binary search on the answer.
## How it works
- Binary search over the range `[0, n]`
- At each step, compute `mid = (low + high) / 2`
- If `mid * mid == n` → return `mid`
- If `mid * mid < n` → potential answer; store `mid`, search right half (`low = mid + 1`)
- If `mid * mid > n` → search left half (`high = mid - 1`)
- Return the stored answer
## When to use
- "Binary search on the answer" pattern — when the answer space is monotone
- Any problem asking for the floor/ceil of a derived value
## Key Points
- Use `long` for `mid * mid` to avoid integer overflow for large `n`
- O(log n) — search space halves each iteration
- Pattern generalizes to: "find the largest x where f(x) is still valid"
Category: algorithms
Difficulty: beginner
Time Complexity: O(log n)
Space Complexity: O(1)
View Square Root (x) Visualization