Newton Method
-
When solving the leetcode 176 Valid Perfect Square, someone introduced a way to find the root of a high class functions.
-
The main idea is by doing tension again and again, we coud get a solution that is close to the root in a accepatble difference.
-
So the linear function for the purple line is: , if we want get the next x(n+1), y = 0.
-
So we could get x by move thing to the other side .
-
In that question(leetcode 367), a square is corresbonded to function like: , .
-
So we get .
-
And the solution for this question is we continue looking for a value that just equals to the number(n), if exist return true otherwise return false. The code is like:
public boolean isPerfectSquare(int num) {
int x = num;
while (x * x > num) {
x = 1/2 * (x + num / x);
}
return x * x == num;
}
-
There is another thing I want to explain is why we use num as n. From the graph of a square function like: , we are trying to find a solution for it,
-
Useful links