Implement int sqrt(int x)
.
Compute and return the square root of x.
题目解析:
这里面比较关键的一个测试数字是:2147395599,
牛顿逼近的方法在46440的时候就停止迭代了。但是算法期待的结果是46339,这边需要特殊处理一下
/************************************************************************/
/*
对于y = sqrt(x),可以将公式转化求y^2-x = 0。x已知求零点。
求解方法可以用牛顿逼近法。
因为y>0则初始选点需要大于0。
*/
/************************************************************************/
#include <iostream>
//#include <cmath>
#define DERIVATIVE_X(x) (2*x)
#define Y_VALUE(x,c) (x*x-c)
#define NEW_X(x,c) (-(Y_VALUE(x,c))/(DERIVATIVE_X(x))+x)
using namespace std;
int sqrt(int x) {
if(x == 0)
return 0;
if(x < 0)
exit(-1);
float init_x = 5;
float derivative_x = DERIVATIVE_X(init_x);
float new_x = NEW_X(init_x,x);
float last_x = init_x;
while(((int)new_x != (int)last_x )||((int)new_x*(int)new_x)>x)
{
last_x = new_x;
new_x = NEW_X(last_x,x);
if( new_x == last_x && ((int)new_x*(int)new_x)>x)
{
new_x = last_x = new_x-1;
}
}
return (int)new_x;
}
int main(void)
{
cout << sqrt(9) << endl;
system("pause");
return 0;
}