0 points

Square Root of a Number


dashboard

Tue Nov 24 2020 16:15:30 GMT+0000 (UTC)

Posted by @snigdhakhurana10

//Square Root of a number without using Math.sqrt() function

function square(num, left, right) {
  let mid = (left + right) / 2,
    sq = mid * mid;
  if (sq === num || Math.abs(sq - num) < 0.00001) return mid;
  else if (sq < num) return square(num, mid, right);
  else return square(num, left, mid);
}

function findSquareRoot(num) {
  let i = 1,
    found = false;
  while (!found) {
    //If num is a perfect square, if condition will return the value
    if (i * i === num) return i;
    else if (i * i > num) {
      let result = square(num, i - 1, i);
      return result;
    }
    i++;
  }
}

let number = 3;
console.log(findSquareRoot(number));
content_copy Copy