Sqrt(x) - Problem
You're tasked with implementing your own integer square root function without using any built-in mathematical functions or operators like pow() or **.
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should also be non-negative.
Key Challenge: You must implement this from scratch - no shortcuts allowed! This problem tests your understanding of mathematical algorithms and efficient searching techniques.
Example: For x = 8, the square root is approximately 2.828, so we return 2 (rounded down).
Input & Output
example_1.py — Basic Case
$
Input:
x = 4
›
Output:
2
💡 Note:
The square root of 4 is exactly 2, so we return 2.
example_2.py — Non-Perfect Square
$
Input:
x = 8
›
Output:
2
💡 Note:
The square root of 8 is approximately 2.828, but we round down to 2.
example_3.py — Edge Cases
$
Input:
x = 0
›
Output:
0
💡 Note:
The square root of 0 is 0.
Constraints
- 0 ≤ x ≤ 231 - 1
- No built-in functions allowed like pow(), sqrt(), or **
- Must return integer result
Visualization
Tap to expand
Understanding the Visualization
1
Set the boundaries
You know the side length is between 0 and the total number of tiles
2
Try the middle
Test if a middle side length works by calculating tiles needed (side²)
3
Adjust search area
If too many tiles needed, try smaller; if tiles left over, try larger
4
Converge to answer
Keep halving the search space until you find the perfect fit
Key Takeaway
🎯 Key Insight: Binary search transforms a linear O(√x) problem into a logarithmic O(log x) solution by intelligently narrowing the search space
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code