blog icon indicating copy to clipboard operation
blog copied to clipboard

平方根

Open wuxianqiang opened this issue 3 years ago • 0 comments

function sqrt(num) {
  function sqrtWrapper(min, max) {
    let current = (min + max) / 2;
    let nextMin = min, nextMax = max;
    if (current * current > num) {
      nextMax = current;
    } else {
      nextMin = current;
    }
    if (min === nextMin && max === nextMax) {
      return current
    }
    else if (nextMax - nextMin < (1 / new Array(17).fill(10).reduce((a, b) => a * b, 1))) {
      return current;
    } else {
      return sqrtWrapper(nextMin, nextMax);
    }
  }
  return sqrtWrapper(0, num);
}
console.time();
console.log(sqrt(3));
console.timeEnd();

wuxianqiang avatar Jul 24 '21 13:07 wuxianqiang