zoukankan      html  css  js  c++  java
  • leetcode--Sqrt(x)

    Implement int sqrt(int x).

    Compute and return the square root of x.

    public class Solution {
        public int sqrt(int x) {
           if(x < 0) return -1;
    		if(x == 0) return 0;
    		
    		//binary search method
    		long 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 small
    				low = mid + 1;
    			else //too large
    				high = 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 root
    			last = iter;
    			iter = (iter + x / iter) / 2;
    		}
    		return (int) iter;
        }
    }
    

      

  • 相关阅读:
    linux 常用命令
    博客园兼容手机端
    博客园点击页面,显示句子
    win10 系统禁止自动更新
    php获取数组中第一个元素或最后一个元素
    设计模式
    高并发抢购
    mySql 数据库优化
    3dMax+VR的安装步骤
    3dmax
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3825205.html
Copyright © 2011-2022 走看看