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 number without using Math.sqrt() in JavaScript
We are required to write a JavaScript function that takes in a positive integer as the only argument. The function should find and return the square root of the number provided as the input.
Newton's Method (Recommended)
The most efficient approach is Newton's method (also called the Babylonian method), which uses iterative approximation to converge on the square root.
const squareRoot = (num, precision = 0) => {
if (num <= 0) {
return 0;
}
let res = 1;
const deviation = 1 / (10 ** precision);
while (Math.abs(num - (res ** 2)) > deviation) {
res -= ((res ** 2) - num) / (2 * res);
}
return Math.round(res * (10 ** precision)) / (10 ** precision);
};
console.log(squareRoot(16));
console.log(squareRoot(161, 3));
console.log(squareRoot(1611, 4));
4 12.689 40.1373
How Newton's Method Works
Newton's method uses the formula: x? = x? - (x?² - n) / (2 * x?), where n is our target number and x? is our current approximation.
// Step-by-step example for ?25
let num = 25;
let guess = 1;
console.log("Finding square root of", num);
console.log("Initial guess:", guess);
for (let i = 0; i < 5; i++) {
guess = guess - (guess * guess - num) / (2 * guess);
console.log(`Iteration ${i + 1}: ${guess}`);
}
Finding square root of 25 Initial guess: 1 Iteration 1: 13 Iteration 2: 7.461538461538462 Iteration 3: 5.406026962727994 Iteration 4: 5.015247601944898 Iteration 5: 5.000012953048684
Binary Search Method
Another approach is binary search, which repeatedly narrows down the range where the square root must exist.
const squareRootBinary = (num, precision = 6) => {
if (num <= 0) return 0;
if (num === 1) return 1;
let start = 0;
let end = num > 1 ? num : 1;
let result = 0;
// Binary search for integer part
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (mid * mid === num) {
return mid;
}
if (mid * mid < num) {
start = mid + 1;
result = mid;
} else {
end = mid - 1;
}
}
// Calculate decimal places
let increment = 0.1;
for (let i = 0; i < precision; i++) {
while (result * result <= num) {
result += increment;
}
result -= increment;
increment /= 10;
}
return parseFloat(result.toFixed(precision));
};
console.log(squareRootBinary(16));
console.log(squareRootBinary(161, 3));
console.log(squareRootBinary(25, 4));
4 12.689 5
Comparison of Methods
| Method | Speed | Precision | Complexity |
|---|---|---|---|
| Newton's Method | Fast | High | Medium |
| Binary Search | Moderate | Good | Low |
Conclusion
Newton's method is the preferred approach for calculating square roots due to its rapid convergence and high precision. Binary search offers a simpler implementation but with slower convergence for high-precision results.
