SQRT (x)
Implement int sqrt(int x)
.
Compute and return the square root of X.
Problem Solving Ideas:
The problem is to find the square root of x.
Solution 1: The basic idea is to enumerate, from 1 to N to traverse until result*result>x, then the result is result-1.
Class Solution {public: int mysqrt (int x) { int result = 0; while (long long) result * result <= x) { result++; } return result-1;} ;
However, this creates a timeout error.
Solution 2: Using a method similar to binary search, the results can be found by binary search in the 0-x interval. Notice that the multiplication may overflow.
Class Solution {public: int mysqrt (int ×) { long long left = 0, right = x; Long Long middle = (left+right)/2; while (left<right) { long long temp = Middle*middle; if (temp = = x) { return middle; } else if (temp > x) {right = middle-1; } else{Left = middle + 1; } Middle = (left + right)/2; } if (Long Long) middle*middle> (long Long) x) { return (int) middle-1; } else{ return (int) middle;}} ;
Solution 3: Newton iterative Method (Reference blog: http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html). Here is the citation.
To facilitate understanding, first take the subject as an example:
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.
after (xi, F (x i)) The tangent equation for this point is f (x) = f (xi) + F ' (Xi) (x-xi", where F ' (x) is the derivative of f (x), 2x in the subject. So that the tangent equation equals 0, you can find Xi+1=xi -F (xi"/F ' (Xi).
Continue to simplify, xi+1=x i -(xi2 -n"/(2xi) = Xi -xi /2 + N/(2xi) = xi /2 + n/2xi = (x i + n/xi)/2.
/sub>
With the iterative formula, the program is ready to write. About Newton's iterative method, you can refer to Wikipedia and Baidu Encyclopedia .
Newton's Iterative method can also be used to solve the multiple-equation solution.
P.S. The problem is to solve the square root of an integer, and the return value is an integral type. A slight modification based on the above code can also be applied to double (method 2 only).
Double sqrt (double x) { if (x = = 0) return 0; Double last = 0.0; Double res = 1.0; while (res! =) {last = res; Res = (res + x/res)/2; } return res;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] SQRT (x)