[leetcode] 【分治法】 69. Sqrt(x)
2016-06-21 00:39
501 查看
Implement
Compute and return the square root of x.
class Solution {
public:
int mySqrt(int x) {
if(x<2) return x;
double begin=0,end=x,mid=1,res=0;
while(abs(res-x)>0.000001)
{
mid=(begin+end)/2;
res=mid*mid;
if(res>x) end=mid;
else begin=mid;
}
return (int)mid;
}
};牛顿迭代法(我没有用这个方法,这题主要练练二分法):
牛顿迭代法(Newton's
method)又称为牛顿-拉夫逊(拉弗森)方法(Newton-Raphson
method),它是牛顿在17世纪提出的一种在实数域和复数域上近似求解方程的方法。
以下代码cur = pre/2 + x/(2*pre)是化简计算的结果。。这里的f(x) = x^2-n
int sqrt(int x).
Compute and return the square root of x.
题意
实现平方根函数,返回x的根。题解
二分法,取到合适的数为止。class Solution {
public:
int mySqrt(int x) {
if(x<2) return x;
double begin=0,end=x,mid=1,res=0;
while(abs(res-x)>0.000001)
{
mid=(begin+end)/2;
res=mid*mid;
if(res>x) end=mid;
else begin=mid;
}
return (int)mid;
}
};牛顿迭代法(我没有用这个方法,这题主要练练二分法):
牛顿迭代法(Newton's
method)又称为牛顿-拉夫逊(拉弗森)方法(Newton-Raphson
method),它是牛顿在17世纪提出的一种在实数域和复数域上近似求解方程的方法。
以下代码cur = pre/2 + x/(2*pre)是化简计算的结果。。这里的f(x) = x^2-n
class Solution { public: int mySqrt(int x) { double pre = 0; double cur = x; // 这里从x开始 从x/2开始会导致 1 不能满足 x(n+1)= xn - f'(xn)/f(xn) while(abs(cur - pre) > 0.000001){ pre = cur; cur = (pre/2 + x/(2*pre)); } return int(cur); } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解