博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
69.Sqrt(x)(二分搜索,牛顿迭代法)
阅读量:2809 次
发布时间:2019-05-13

本文共 1602 字,大约阅读时间需要 5 分钟。

题目:

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4

Output: 2

Example 2:

Input: 8

Output: 2
Explanation: The square root of 8 is 2.82842…, and since
the decimal part is truncated, 2 is returned.

解析:求数x的开平方。

方法一:二分搜索。参考http://www.cnblogs.com/grandyang/p/6854825.html。思路是求一个候选值的平方,与目标值x比较大小。找最后一个不大于目标值的数。

class Solution {public:    int mySqrt(int x) {        if(x<=1) return x;//这一句不可缺少,对于特殊情况的单独处理。缺少它会报错        int left=0,right=x;        while(left < right)        {            int mid = left+(right-left)/2;            if(x/mid >= mid) left=mid+1;            else right=mid;        }        return right-1;    }};

方法二:牛顿迭代法。

class Solution {public:    int mySqrt(int x) {        if(x == 0) return 0;        double last,res;//注意这里的类型        last=0,res=1;        while(abs(last-res)>1e-6)//循环条件是前后两个解xi和xi-1是否无限接近        {            last = res;            res = (res+x/res)/2;          }        return (int)res;//类型强制转换为int    }};

牛顿迭代法详解:

计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如下图所示。

首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交点为x1。

同样的道理,如果x1不是解,做一个经过(x1,f(x1))这个点的切线,与x轴的交点为x2。

以此类推。

以这样的方式得到的xi会无限趋近于f(x)=0的解。

判断xi是否是f(x)=0的解有两种方法:

一是直接计算f(xi)的值判断是否为0,二是判断前后两个解xi和xi-1是否无限接近。

经过(xi, f(xi))这个点的切线方程为f(x) = f(xi) + f’(xi)(x - xi),其中f’(x)为f(x)的导数,本题中为2x。令切线方程等于0,即可求出xi+1=xi - f(xi) / f’(xi)。

继续化简,xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2。

在这里插入图片描述

你可能感兴趣的文章
结构体的三种定义方式
查看>>
[Java]生成随机数
查看>>
[Linux]解压命令
查看>>
oj之输入输出
查看>>
[排序]
查看>>
[排序]
查看>>
[日期类问题]例 2.3 日期差值 (九度教程第 6 题)
查看>>
[日期类问题] 例 2.4 Day of week(九度教程第 7 题)
查看>>
c++stack容器介绍
查看>>
dijstra最短路径
查看>>
竖式问题
查看>>
关于C++中形参 *&
查看>>
[递归]CODEVS-3145 汉诺塔游戏
查看>>
Tips
查看>>
字符串相关Tips
查看>>
[深搜]CODEVS-1501 二叉树最大宽度和高度
查看>>
[模拟]CODEVS-1083 Cantor表
查看>>
[模拟]CODEVS-1160 蛇形矩阵
查看>>
[软件体系结构]DCOM,CORBA,EJB介绍
查看>>
[链表]九度OJ-1517:链表中倒数第k个结点
查看>>