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.

Example

Following is the code −

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

Output

Following is the output on console −

4
12.689
40.1373

Updated on: 11-Dec-2020

605 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements