← Back to DSA mapEasy
Binary Search
Square Root without Math.sqrt
Find a square root to 2 decimal places by repeatedly halving the range.
Problem
Write a function that calculates the square root of a non-negative number without using Math.sqrt(). The result must be accurate to 2 decimal places.
- Do not use Math.sqrt() or ** 0.5.
- Return NaN for negative input.
- The result must be accurate to 2 decimal places, including for numbers below 1.
Examples
Input: n = 144
Output: 12
Input: n = 2
Output: 1.41
Input: n = 0.25
Output: 0.5
For numbers below 1, the root is bigger than the number.
Approach
Time O(log(n / ε))Space O(1)
- The root lies between 0 and max(1, n). The max matters: for n < 1 the root is larger than n, so a range of [0, n] would miss it.
- Take mid of the range. If mid² < n the root is above mid, so move low up; otherwise move high down.
- Each step cuts the range in half, so the answer gets one bit more precise every time. 100 halvings is far more than 2 decimal places need.
- Round the result to 2 decimals.
Common mistakes
- Using [0, n] as the starting range fails for n < 1.
- Stopping when |n - guess²| is small is not the same as the guess being accurate to 2 decimals - check the precision of the guess itself.
- Looping until high - low is tiny can run forever on huge numbers, because decimals in a computer cannot get that close together. Running a fixed number of steps avoids that.
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
Edit and run it here
JavaScript solution
Loading...
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
All courses
24 courses in 5 subjects
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned
Frontend
Fundamentals
On this page
0 sections