在不使用Math.sqrt()JavaScript的情况下查找非负数的平方根
我们需要编写一个JavaScript函数,该函数接受一个非负的Integer并计算并返回其平方根。我们可以将浮点数下限为整数。
例如:对于数字15,我们无需返回精确值,我们只需返回最接近的较小整数值(在15的情况下为3)即可。
我们将使用二进制搜索算法来转换给定数字的平方根。
为此的代码将是-
示例
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));输出结果
控制台中的输出将是-
2 27 3 233
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短