Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

2 solutions: bin-search and Newton iteration.

class Solution {
public:
    int _sqrt(long long tgt, long long i0, long long i1)
    {
        long long cand = (i0 + i1) / 2;
        if (cand * cand == tgt) return cand;
        if (cand * cand > tgt)     return _sqrt(tgt, i0, cand);
        else if(cand * cand < tgt)
        {
            if((cand + 1)*(cand + 1) > tgt) return cand;
            if((cand + 1)*(cand + 1) == tgt) return cand + 1;
            return _sqrt(tgt, cand + 1, i1);
        }
    }
    int sqrt(int x) {
        if (x == 1) return 1;
        return _sqrt(x, 1, x/2);
    }
};
posted on 2014-07-23 05:41  Tonix  阅读(170)  评论(0)    收藏  举报