x的平方根

102 阅读1分钟

leetcode: 69. x 的平方根

题目描述

给你一个非负整数 x ,计算并返回 x 的 算术平方根 。

由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。

注意: 不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。

示例

输入: x = 4
输出: 2

解题思路

二分法找第一个小于等于x平方根的整数。

class Solution {
    public int mySqrt(int x) {
        int l = 0, r = x;
        while (l <= r) {
            int mid = (l + r) / 2;
            long prod = (long) mid * mid;
            if (prod == x) {
                return mid;
            }
            else if (prod < x) {
                l = mid + 1;
            }
            else {
                r = mid - 1;
            }
        }
        return r;
    }
}

牛顿迭代法

显然,方程 y=f(x)=x2Cy = f(x) = x^2 - C的零点就是C的平方根。

求解方程f(x) = 0。

f(x)在x某个邻域的泰勒展开为f(x)=x0+f(x)(xx0)1!+...+fn(x)(xx0)nn!+Rn(n)f(x) = x_0 + {\frac {f^{'}(x) (x - x_0)}{1!}} + ... + {\frac {f^{n}(x) (x - x_0)^n}{n!}} + R_n(n)

取前两项x0+f(x)(xx0)1!=0x_0 + {\frac {f^{'}(x) (x - x_0)}{1!}} = 0 的求解结果, 作为方程f(x) = 0的近似解。

牛顿迭代 xn+1=xnf(xn)f(xn)x_{n+1} = x_n - \frac{f(x_n)}{f^{'}(x_n)},迭代逼近近似解。

class Solution {
    public int mySqrt(int x) {
        long res = x;
        while (res * res > x) {
            res = (res + x / res) / 2;
        }
        return (int) res;
    }
}