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. We can floor off a floating-point number to an integer.

For example: For the number 15, we need not to 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 converse to the square root of the given number.

The code for this will be −

Example

const squareRoot = (num = 1) => {
   let l = 0; let r = num; while(l <= r) {
      const mid = Math.floor((l + r) / 2);
      if(mid ** 2 === num){ return mid;
         }else if(mid ** 2 > 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));

Output

And the output in the console will be −

2
27
3
233

Updated on: 21-Nov-2020

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements