c_cpp 实施sqrt

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 实施sqrt相关的知识,希望对你有一定的参考价值。

int sqrt(int x) {
    if(x == 0) return 0;
    if(x == 1) return 1;
    int i = 0, j = x;
    
    while(i <= j) {
        float m = i + (j-i)/2;
        long long q = m*m;
        if(q == x)
            return m;
        else if(q < x)
            i = m+1;
        else 
            j = m-1;
    }
    return j; // return j not i is because j < i. We use the smaller one.
}

// sqrt for double precision
double sqrt(double x) {
    const double EPS = 1e-6;
    double low = 0, high = x; // should be double not int here
    while(low + EPS < high) {  // gist, note this predicate! 
        double mid = (low + high) / 2;
        if(mid * mid > x) high = mid;
        else low = mid;
    }
    return low;            // it seems that returning'low' or 'high' will have the same results
}



以上是关于c_cpp 实施sqrt的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp CPP:树实施

c_cpp 实施一个特里

c_cpp 实施红黑树

c_cpp BST实施和遍历

c_cpp 双重链表实施

c_cpp 双重链表OO实施