在不使用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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短