Square Root--conquer

Source: Internet
Author: User
Tags square root

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.