Finding square root of a number without using library functions - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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

Example

Following is the code −

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));

Output

This will produce the following output in console −

5.744562149047852

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.

raja
Published on 30-Sep-2020 18:05:30
Advertisements