JSFiddle - React, Tailwind, and code Playground

Square root using binary search algorithm, with some magic

by Yurii Predborskyi

JavaScript

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
  let left = 0;
  let right = x - 1;
  let val = 0;
  while (left <= right) {
  	val = left + Math.floor((right - left) / 2);
    let square = val * val;
    if (square === x) {
    	break;
    } else if (square > x) {
    	right = val - 1;
    } else if (square < x) {
    	left = val + 1;
    }
  }
  return val * val > x ? val - 1 : val;
};

let tests = [
  { x: 4, answer: 2 },
  { x: 8, answer: 2 },
  { x: 9, answer: 3 },
  { x: 10, answer: 3 },
  { x: 11, answer: 3 },
  { x: 12, answer: 3 },
  { x: 13, answer: 3 },
  { x: 14, answer: 3 },
  { x: 15, answer: 3 },
  { x: 16, answer: 4 },
];

tests.forEach(test => {
  let res = mySqrt(test.x);
  console.log(res, res === test.answer);
});