*SQRT (x)

Source: Internet
Author: User

Q:

Implement int sqrt (int x).

Compute and return the square root of X.

A:

Here are two methods of implementation: One is binary search, the other is Newton iterative method.

1.Two-point search

For a non-negative n, its square root is no greater than (n/2+1). In [0, n/2+1] This range can be a binary search, to find the square root of N.

1  Public classSolution {2      Public intMYSQRT (intx)3     {4        5      Longi = 0;6      Longj = x/2 + 1;7      while(I <=j)8     {9          LongMid = (i + j)/2;Ten          LongSq = Mid *mid; One         if(sq = = x)return(int) mid; A         Else if(Sq < x) i = mid + 1; -         Elsej = Mid-1; -     } the     return(int) J; -  -     } -}

Reference

Http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

*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.