zoukankan      html  css  js  c++  java
  • 69. Sqrt(x)

    Implement int sqrt(int x).

    Compute and return the square root of x.

    1.

    class Solution {
    public:
        int mySqrt(int x) {
            if(x == 0 || x == 1)
                return x;
            int l=1, r=x/2+1, m;
            while(l<=r)
            {
                m = (l+r)>>1;
                long long mul = (long long)m*(long long)m;
                if(mul > x)
                    r = m-1;
                else if(mul < x)
                    l = m+1;
                else
                    return m;
            }
            return r;
        }
    };

    注意:

    long long mul = (long long)m*(long long)m;
    这一句中,要先将m转换为long long型,再相乘。

    2. Newton's Method

    // http://en.wikipedia.org/wiki/Newton%27s_method
    int sqrt_nt(int x) {
        if (x == 0) return 0;
        double last = 0;
        double res = 1;
        while (res != last)
        {
            last = res;
            res = (res + x / res) / 2;
        }
        return int(res);
    }
  • 相关阅读:
    多项式学习笔记(二) NTT
    矩阵树定理学习笔记
    拓展BSGS 学习笔记
    P2257 YY的GCD
    P1891 疯狂的lcm
    友链
    关于我
    焚燃指间の回忆
    洛谷P4180
    洛谷P2292
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5272178.html
Copyright © 2011-2022 走看看