Description:
Implement int sqrt(int x)
.
Compute and return the square root of X.
It is very useful to study maths well, and Newton's iterative method solves it.
computes thesolution of x 2 = n, making f (x) =x2-n equivalent to solving the solution of the F (x) =0, as shown in the figure on the left.
First Take x0, if x0 is not a solution, make atangent to the point (X 0,f (x0)), and the x-axis intersection is x1.
Similarly, if X1 is not a solution, make atangent of this point (x 1,f (x1)), and the x-axis intersection is x2.
And so on
The x I obtained in this wayis infinitely nearer to the solution of f (x) =0.
There aretwo ways to determine if x i is an F (x) =0 solution:
First, the direct calculation of the value of f (x i) is 0, and the second is to judge whether the two solutions xI and xi-1 are infinitely close.
public class Solution {public int mysqrt (int x) { if (x ==0) return 0; Double pre; Double cur = 1; Do { pre = cur; cur = x/(2 * pre) + pre/2.0; } while (Math.Abs (cur-pre) > 0.00001); return (int) cur;} }
LEETCODE--SQRT (x)