Description of title narrative:
No sqrt (x) library functions are required. In order to achieve the square root.
Problem Solving Ideas:
Using dichotomy
Assuming the square root of num is required, then first take the midpoint mid between 1~num.
If mid * mid > num, then the root is between 1~mid-1.
If Mid * mid < Num, then the root is between mid+1~num.
If mid * mid = = num, direct output mid;
Because integer int, the square root is rounded down. So. If mid * Mid < X are in the case, the root may be mid. According to the above if the root is between Mid+1~num, then the mid+1~num between all the heel is greater than Num.
So you have to deal with it when you exit.
<span style= "FONT-SIZE:18PX;" >IF (Min*min > num) return min-1;else return min;</span>
Reference Code:
<span style= "FONT-SIZE:18PX;" >class solution{public:int getsqrt (int num) { if (num <= 0) return 0;int min = 0;int max = Num;int mid = (min + ma x)/2;int mark = 0.001;while (min <= max) {if (mid*mid = = num) return mid;else if (Mid*mid < num) min = Mid+1;elsemax = Mid-1;mid = (min + max)/2;} if (min * min > num) return min-1;else return min;}}; </span>
Code Listing 2: Consider the accuracy estimated number equal to the square root of Num. The precision is defined by itself, using the same dichotomy.
float getsqrt (int num, float epsilon) { if (num <=0) return 0;float low, high, Maymid;low = 0;high = max (1, num); Maym ID = (low + high)/2.0;while (ABS (Maymid*maymid-num) >epsilon) {if (MAYMID * maymid = num) return maymid;if (Maymid*ma Ymid<num) low = Maymid;elsehigh = Maymid;maymid = (low + high)/2.0;} return maymid;}
References:
http://blog.csdn.net/tosslee/article/details/6998448
http://blog.csdn.net/u012162613/article/details/41361655
Square Root--conquer