Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding square root of a non-negative number without using Math.sqrt() JavaScript
We are required to write a JavaScript function that takes in a non-negative integer and computes and returns its square root without using Math.sqrt(). We can floor off a floating-point number to an integer.
For example: For the number 15, we need not return the precise value, we can just return the nearest smaller integer value that will be 3, in case of 15.
We will make use of the binary search algorithm to converge to the square root of the given number.
Binary Search Approach
The binary search method works by maintaining a range [left, right] where the square root must lie, then narrowing this range by checking the middle value.
const squareRoot = (num = 1) => {
let l = 0;
let r = num;
while (l num) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return r;
};
console.log(squareRoot(4));
console.log(squareRoot(729));
console.log(squareRoot(15));
console.log(squareRoot(54435));
2 27 3 233
How It Works
The algorithm starts with a search range from 0 to the input number. At each step:
- Calculate the middle value of the current range
- If mid² equals the target number, we found the exact square root
- If mid² is greater than the target, the square root is in the left half
- If mid² is less than the target, the square root is in the right half
Alternative: Newton's Method
Another efficient approach uses Newton's iterative method for finding square roots:
const squareRootNewton = (num) => {
if (num === 0 || num === 1) return num;
let x = num;
let root;
while (true) {
root = Math.floor(0.5 * (x + num / x));
if (Math.abs(root - x)
4
5
7
Comparison
| Method | Time Complexity | Space Complexity | Accuracy |
|---|---|---|---|
| Binary Search | O(log n) | O(1) | Integer floor result |
| Newton's Method | O(log n) | O(1) | Faster convergence |
Conclusion
Both binary search and Newton's method provide efficient alternatives to Math.sqrt(). Binary search is more intuitive, while Newton's method converges faster for larger numbers.
