不用库函数sqrt()求一个正整数N的开方

两种方法:
1.牛顿迭代

int _tmain(int argc, _TCHAR* argv[])  
{  
    int N;    
    cout<<"输入N的值:";    
    cin>>N  ;  

    double x1 = 1;//初值    
    double x2 = x1/2.0+N/2.0/x1;    

    while( fabs(x2-x1)>0.001)    
    {    
        x1 = x2;    
        x2 = x1/2.0+N/2.0/x1;    
    }    
    cout<return 0;  
}  

2.二分法
若N大于1,则从[1, N]开始,low = 1, high = N, mid = low + (high - low) 》 1开始进行数值逼近
若N小于1,则从[N, 1]开始,low = 0, high = N, mid = low + (high - low) 》 1开始进行数值逼近

   #define ACCURACY 0.001
    double newSqrt(double n)
    {
    double low, high, mid, tmp;
    // 获取上下界
    if (n > 1)
    {
    low = 1;
    high = n;
    } else {
    low = n;
    high = 1;
    }
    // 二分法求开方
    while (low <= high) {
    mid = (low + high) / 2.000;
    tmp = mid * mid;
    if (tmp - n <= ACCURACY && tmp -n >= ACCURACY * -1) {
    return mid;
    } else if (tmp > n) {
    high = mid;
    } else {
    low = mid;
    }
    }
    return -1.000;
    }

你可能感兴趣的:(算法基础学习)