Short and Fast Newton method in JAVA with Explaination


  • 0
    W

    If "res" is the root of x, then "res^2 - x == 0", f(x) is "res^2 - x", f'(x) is "2 * res". Now we plot f(x) and use the derivative of f(x) (slop of the graph, which is f'(x)) to find it's intersection with Y axis(when f(x) equals 0): "newRes = oldRes - f(x) / f'(x)".

    public class Solution {
        public int mySqrt(int x) {
            double oldRes = 1;
            double newRes = 1.1;
            while (Math.abs(oldRes - newRes) > 0.01) {
                double tmp = (oldRes + x / oldRes) / 2;
                oldRes = newRes;
                newRes = tmp;
            }
            return (int) newRes;
        }
    }

Log in to reply
 

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