Problem:
Implement int sqrt(int x) .
Compute and return the square root of X.
Hide TagsMath Binary SearchTest instructions: Calculates square root, no precision specified, default precision is 0.00001
Thinking:
(1) Because the problem does not set the accuracy, suggesting the use of binary method
(2) In addition to the dichotomy, you can also use Newton's iterative
Code
Two-part method:
Class solution{public : int sqrt (int x) { unsigned long long begin = 0; unsigned long long end = (x+1)/2; unsigned long long mid; unsigned long long tmp; while (begin < End) { mid = begin + (End-begin)/2; TMP = Mid*mid; if (tmp==x) return mid; else if (tmp<x) begin = mid+1; else end = Mid-1; } TMP = End*end; if (tmp > x) return end-1; else return end;} };
Newton Iteration:
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-x< Sub style= "margin:0px; padding:0px ">i", 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 xi+1= (xi + n/xi)/2, the program is ready to write. About Newton's iterative method, you can refer to Wikipedia and Baidu Encyclopedia .
Class Solution {public: int sqrt (int x) { if (x<0) return-1; Double a=1.0; Double check=0; do{ a= (x/a+a)/2; check = A*a; } while (ABS (CHECK-X) >0.00001); return A; };
Leetcode | | 69, SQRT (x)