LEETCODE--SQRT (x)

Source: Internet
Author: User

Description:

Implement int sqrt(int x) .

Compute and return the square root of X.

It is very useful to study maths well, and Newton's iterative method solves it.

computes thesolution of x 2 = n, making f (x) =x2-n equivalent to solving the solution of the F (x) =0, as shown in the figure on the left.

First Take x0, if x0 is not a solution, make atangent to the point (X 0,f (x0)), and the x-axis intersection is x1.

Similarly, if X1 is not a solution, make atangent of this point (x 1,f (x1)), and the x-axis intersection is x2.

And so on

The x I obtained in this wayis infinitely nearer to the solution of f (x) =0.

There aretwo ways to determine if x i is an F (x) =0 solution:

First, the direct calculation of the value of f (x i) is 0, and the second is to judge whether the two solutions xI and xi-1 are infinitely close.

public class Solution {public    int mysqrt (int x) {        if (x ==0)             return 0;          Double pre;          Double cur = 1;          Do          {              pre = cur;              cur = x/(2 * pre) + pre/2.0;          } while (Math.Abs (cur-pre) > 0.00001);          return (int) cur;}              }

LEETCODE--SQRT (x)

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.