在不使用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 教师闺蜜祝福语简短