SQRT (x)
Implement int sqrt(int x) .
Compute and return the square root of X.
Solution One: Newton Iterative method
Find the square root of N, that is, 0 points of F (x) =x2-n
Set the initial value of x0, note, do not set to 0, so as to avoid a divisor of 0, see after.
The tangent of the (x0,f (x0)) point is g (x) =f (x0) +f ' (x0) * (x-x0)
The intersection of G (x) and X axis is x1=x0-f (x0)/F ' (x0)
Recursion relationship is xn+1=xn-f (xn)/f ' (xn)
It is the solution when it is convergent.
classSolution { Public: intsqrtintx) {Doublex0 =1; Doublexn = (x0+x/x0)/2; while(ABS (X0-XN) > 1e-5) {x0=xn; Xn= (x0+x/x0)/2; } returnx0; }};
2:2 Method of Solution
Note that the return is int, and the result is rounded.
classSolution { Public: intsqrtintx) {Long LongLow =0; Long LongHigh =x; Long Longmid; while(Low <=High ) {Mid= (Low+high)/2; Long Longresult = mid*mid; if(Result = =x)returnmid; Else if(Result >x) High= mid-1; Else Low= mid+1; } returnHigh ; }};
"Leetcode" Sqrt (x) (2 solutions)