[Lintcode]sqrt (x)

Source: Internet
Author: User

Method 1: Two points

1 classSolution {2  Public:3     /**4 * @param x:an integer5 * @return: The sqrt of x6      */7     intsqrtintx) {8         //Write your code here9         Long LongL =1, r =x;Ten          while(l<R) One         { A             Long Longm = (l+r)/2; -             if(m*m>x) r = m1; -             Else the             { -                 if((m+1) * (m+1) >x)returnm; -                 Else -                 { +L = m+1; -                 } +             } A         } at     } -};

Method 2: Newton's method

Ask for the square root of x, first any number y, if y is not the square root of x or the precision is not enough, then y = (y+x/y)/2, loop until the square root of x or achieve our satisfactory accuracy, each cycle will make y closer to the square root of x.

1#include <cmath>2 classSolution {3  Public:4     /**5 * @param x:an integer6 * @return: The sqrt of x7      */8     intsqrtintx) {9         //Write your code hereTen         Doubley =1.0; One          while(ABS (Y*Y-X) >1) Ay = (y+x/y)/2; -         return(int) y; -     } the};

[Lintcode]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.