Nine chapters algorithm surface question 71 square root

Source: Internet
Author: User

Nine Chapters count judges Net-original website

http://www.jiuzhang.com/problem/72/


Topics

Given a number, the answer to its square root can be obtained without the sqrt of the system function.


Online test

http://www.lintcode.com/en/problem/sqrtx/


Answer

We have two methods for this topic:


Method 1:2-point method. We know that if Y represents the value of the square root of x, then we can determine the 0<=y<x, so we can set a min=0,max=x, and then each time using a two-point method to obtain mid= (Min+max)/2, and then just compare mid^2 with X, if mid^2 <x, then Max=mid continue two points, and vice versa mid^2>x, then Min=mid continue two points. Until a mid is found, the square closest to X is good.


Method Two: Newton iterative method. Computes the solution of x^2 = N, making f (x) =x^2-n equivalent to solving the solution of f (x) =0. First take a point x0 for a larger number, if x0 is not a solution, do a pass (x0,f (x0)) This point tangent, and the x-axis intersection is x1, see X1 is not the solution. If not, then continue to do a pass (x1,f (x1)) This point tangent to the x-axis intersection is x2, and then see X2 is not the solution. The process is then repeated, after (XI, F (xi)), the tangent equation for this point is f (x) = f (xi) + F ' (xi) (X-XI), where F ' (x) is the derivative of f (x), 2x in the subject. Xi+1=xi-f (xi)/F ' (xi) can be obtained by making the tangent equation equal to 0. With the iterative formula, the solution of the final equation can be obtained by the infinite approximation of the iterative formula.


Continue simplifying, xi+1=xi-(xi2-n)/(2XI) = XI-XI/2 + N/(2xi) = XI/2 + N/2xi = (xi + n/xi)/2.

Nine chapters algorithm surface question 71 square root

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.