Skip to content

LeetCode题解:69. x 的平方根,牛顿迭代法+迭代,JavaScript,详细注释 #283

@chencl1986

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/sqrtx/

解题思路:

  1. 要理解牛顿迭代法,我们需要先回顾一下导数,或者可以看这一篇导数入门
  2. 题解参考了二分查找 + 牛顿法(Python 代码、Java 代码)牛顿迭代法69. x 的平方根-二分查找, 牛顿法
  3. 根据题意,该题是这样一个方程$x^{2}=a$,已知$a$求$x$。可以将其用函数$f(x)=x^{2}-a$代替。
  4. 这个函数的导数是$2x$,也就是$2x_0=\cfrac{f(x)-f(x_0)}{x-x_0}$。
  5. 将$f(x)=0$带入,可以得到$2x_0=\cfrac{-f(x_0)}{x-x_0}$。
  6. 将$f(x_0)=x_0^{2}-a$带入,可以得到$2x_0=\cfrac{a-x_0^{2}}{x-x_0}$。
  7. 将等式整理,可以得到$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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions