141. SQRT (x) "Newton iterative method for square root by Java"

Source: Internet
Author: User
Tags square root

Description

Implement int sqrt(int x) .

Compute and return the square root of X.

Example

sqrt (3) = 1

sqrt (4) = 2

sqrt (5) = 2

sqrt (10) = 3

Challenge

O (log (x))

Test instructions: To find the square root of a given number, if you use a general method, such as a dichotomy, you need to consider the scope of the int type, do not overflow. The best method when Newton iterative method. The code is as follows:

 Public classSolution {/**     * @paramX:an Integer *@return: The sqrt of x*/     Public intsqrtintx) {//Write your code here//Newton's iterative method to find square root       Doublep=2.0; DoublePre=0;  while(Math.Abs (P-pre) >1e-6) {Pre=p; P= (p+x/p)/2.0; }       return(int) p; }}

On the application principle of Newton iterative method on square root, see blog: http://www.matrix67.com/blog/archives/361

141. SQRT (x) "Newton iterative method for square root by Java"

Related Article

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.