4-line code with Newton iteration(2ms)


  • 2
    Z

    To estimate the root of f(x), in each iteration, we update x with :
    x(j+1) = x(j) - f(x(j)) / f'(x(j))
    In this problem, f(x) = x^2 - a
    a represents the original number which we want to find the square root.

    public int mySqrt(int x) {
        double y = 600.1;
        for(int i = 0; i < 10; ++i)
            y = 0.5 * y + x * 0.5 / y;
        return (int)y;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.