Leetcode -- SQRT (X)

Source: Internet
Author: User

Implementint sqrt(int x).

Compute and return the square rootX.

public class Solution {    public int sqrt(int x) {       if(x < 0) return -1;if(x == 0) return 0;//binary search methodlong high = x / 2 + 1;long low = 0;while(low <= high) {long mid = low + (high - low) / 2;long approximateSquare = mid * mid;if(approximateSquare == x)return (int) mid;if(approximateSquare < x) //too smalllow = mid + 1;else //too largehigh = mid - 1;}return (int) high;    }}

 

Newton Iteration Method (X _ {I + 1} = x_ I-F (x_ I)/f ^ '(x_ I). Where f ^' (x_ I) = 2x_ I in this problem.

Therefore, X _ {I + 1} = x_ I-(x_ I ^ 2-x)/2x_ I = (x_ I + x/X_ I)/2. the algorithm converges to the root, so the termination condition of the loop is X _ {I }== X {I + 1}

public class Solution {    public int sqrt(int x) {        if(x < 0) return -1;if(x == 0) return 0;double last = 0;double iter = 1;while(last != iter){ //termination condition. the algorithm converges to the rootlast = iter;iter = (iter + x / iter) / 2;}return (int) iter;    }}

  

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.