-
Notifications
You must be signed in to change notification settings - Fork 86
Open
Description
原题链接:https://leetcode-cn.com/problems/sqrtx/
解题思路:
- 要理解牛顿迭代法,我们需要先回顾一下导数,或者可以看这一篇导数入门。
- 题解参考了二分查找 + 牛顿法(Python 代码、Java 代码)、牛顿迭代法、69. x 的平方根-二分查找, 牛顿法。
- 根据题意,该题是这样一个方程$x^{2}=a$,已知$a$求$x$。可以将其用函数$f(x)=x^{2}-a$代替。
- 这个函数的导数是$2x$,也就是$2x_0=\cfrac{f(x)-f(x_0)}{x-x_0}$。
- 将$f(x)=0$带入,可以得到$2x_0=\cfrac{-f(x_0)}{x-x_0}$。
- 将$f(x_0)=x_0^{2}-a$带入,可以得到$2x_0=\cfrac{a-x_0^{2}}{x-x_0}$。
- 将等式整理,可以得到$x=\cfrac{x_0+\cfrac{a}{x_0}}{2}$。
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function (x) {
let x0 = x; // 缓存每次迭代的结果,从x开始迭代
// 用Math.floor将x0*x0向下取整
// 避免例如TestCase: 5,会出现x0 * x0=5.000000000000001,造成死循环
while (Math.floor(x0 * x0) > x) {
// 套用分析得到的迭代公式,不断迭代
// 当迭代结束时,得到的就是最接近结果的值
x0 = (x0 + x / x0) / 2;
}
// 将结果的整数部分返回
return Math.floor(x0);
};
Metadata
Metadata
Assignees
Labels
No labels