Square root function without using Math.sqrt() in JavaScript

We are required to write a JavaScript function that takes in a number and calculates its square root without using the Math.sqrt() function.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const square = (n, i, j) => {
let mid = (i + j) / 2;
let mul = mid * mid;
if ((mul === n) || (Math.abs(mul - n) < 0.00001)){
return mid;
}else if (mul < n){
return square(n, mid, j);
}else{
return square(n, i, mid);
}
}
// Function to find the square root of n
const findSqrt = num => {
let i = 1;
const found = false;
while (!found){
// If n is a perfect square
if (i * i === num){
return i;
}else if (i * i > num){
let res = square(num, i - 1, i);
return res;
};
i++;
}
}
console.log(findSqrt(33));

Understanding the code

We looped over from i = 1. If i * i = n, then we returned i as n is a perfect square whose square root is I, else we find the smallest i for which i * i is just greater than n.

Now we know the square root of n lies in the interval i – 1 and i.

And then we used the Binary Search algorithm to find the square root.

Output

The output in the console will be −

5.744562149047852