SQRT (x)

Source: Internet
Author: User

SQRT (x)

Implement int sqrt(int x) .

Compute and return the square root of x. Analysis: Scenario One: Traverse 0~n, first occurrence i * i > N,Return to I-1.  Scenario 2:2 Search: (1) when n = 0, or n = 1 o'clock, returns N (2) initialized s = 0, E = n; Note that the value of E must not exceed Int_max's root value, i.e. E is not greater than46341, otherwise the mid * mid value may overflow, resulting in an error in the calculation result.                (3) When S < E, Mid = (s + e)/2;               When Mid * Mid < N, s = mid;               When Mid * mid > N, e = mid;               When mid * mid = N, return mid. When s + 1 = e, the description s * S < n < (s + 1) * (S + 1), i.e. S is the evaluated value. Otherwise, the loop continues to execute.
1 classSolution2 {3  Public:4   intsqrtintN)5   {6     intm =N;7     if(n = =0|| n = =1)8       returnN;9 Ten     ints =0, E = N, mid =0; One     if(E >46341) AE =46341; -     -      while(S <e) the     { -Mid = (s + e)/2; -       if(Mid * Mid <N) -s =mid; +       Else if(Mid * mid >N) -E =mid; +       Else A         returnmid; at  -       if(S +1==e) -         returns; -     } -   } -};

SQRT (x)

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.