题解 | #求平方根#
求平方根
https://www.nowcoder.com/practice/09fbfb16140b40499951f55113f2166c
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param x int整型
* @return int整型
*/
function sqrt( x ) {
// write code here
return Math.floor(Math.sqrt(x));
}
module.exports = {
sqrt : sqrt
};
库函数秒了
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param x int整型
* @return int整型
*/
function sqrt( x ) {
// write code here
function mySqrt(a, epsilon = 1e-6) {
let x = a / 2;
while (Math.abs(x * x - a) > epsilon) {
x = x - (x * x - a) / (2 * x);
}
return x;
}
return Math.floor(mySqrt(x));
}
module.exports = {
sqrt : sqrt
};
牛顿迭代法:牛顿迭代法(Newton's method)是一种求解方程的方法,可用于计算平方根。通过迭代公式不断逼近平方根的值。
使用误差容忍度,用于控制迭代的停止条件
