完全平方数的判定及整数平方根的快速求解

原帖:http://hi.baidu.com/atyuwen/blog/item/206369fdae6d221e09244da9.html

在上个星期的“有道难题”网络预赛中,某些Group的第二题涉及到了完全平方数的判定问题。相信大多数人的判定语句都差不多是这样写的:if(sqr((int)sqrtl(n))==n){...},把这条语句整理一下,大概是这样:

inline __int64 sqr(int n){return static_cast<__int64>(n)*n;}

inline int directSqrt(int n)
{
    int root = static_cast<int>(sqrtl(n));
    if (sqr(root+1) <= n)
     {
        return root + 1;
     }
    else return root;
}

inline bool isSquareNumber(int n)
{
  int root = directSqrt(n);
  return sqr(root) == n;
}

这个判定方法主要是利用标准库的sqrt函数来求整数平方根(integer square root),正确性不用怀疑,效率也足够。但是如果想要更快呢?通常来说,要判定任意一个数是否是完全平方数,求根的过程在所难免。但是,标准库的sqrt函数是求浮点平方根的,而我们只需要获取整数平方根即可,所以在这里肯定还有性能提升的空间。于是接下来就列举一些计算整数平方根的方法(后两个算法不是我写的),按照计算速度从慢到快依次排列,其中最后一个算法的效率大概是上述直接利用sqrtl的方法的四倍。

1. 线性搜索,直接从小到大依次取数试探,最原始的办法,代码如下:

inline int linearSqrt(int n)
{
    int i = 0;
    while (sqr(i) <= n) ++i;
    return i-1;
}


2. 二分法寻找根

inline int bisectionSqrt(int n)
{
    int l = 0, r = n/2 + 1;
    while (r - l > 1)
     {
        int m = (l+r)/2;
         __int64 sqrm = sqr(m);
        if (sqrm == n)
         {
            return m;
         }
        else if (sqrm > n) r = m;
        else l = m;
     }
    
    if (sqr(r) == n)
     {
        return r;
     }
    else return l;
}

3. 牛顿迭代法,令方程 x^2 - n = 0,则求sqrt(n)也即是求这个方程的根,根据牛顿法的迭代公式有:x' = x - (x^2-n)/(2x) = (x^2+n)/(2x),选定合适的初始值迭代,很快就能收敛到根。另外,这个迭代其实也就是不动点迭代的松弛形式,由 x^2= n => x = n/x, 得不动点迭代x' = n/x,加上松弛系数1/2(算数平均),得x'= 1/2 * (x + n/x),即 x' = (x^2+n)/(2x),与前面牛顿法的迭代公式相同。算法的代码如下:

inline int newtonSqrt(int n)
{
    static int table[16] = {
        1, 1<<2, 1<<4, 1<<6, 1<<8, 1<<10, 1<<12, 1<<14, 1<<16,
        1<<18, 1<<20, 1<<22, 1<<24, 1<<26, 1<<28, 1<<30,
     };
     unsigned i = 0, x0 = 0, x1 = 0;
    while (table[i] < n && i!=16) ++i; x0 = 1 << i;
    while (x0 != 0)
     {    
         x1 = static_cast<int>((sqr(x0) + n)/ (2*x0));
        if (x1 >= x0)
         {
            break;
         }
         x0 = x1;
     }
    return x0;
}

4. 逐位确定法,从高到低依次确定根的各个二进制位。见下面这个代码,看起来似乎很飘逸,但实际上算法很简单明晰,具体的解释可以搜索James Ulery的论文:"Computing Integer Square Roots".

inline int fastIntSqrt(int n)
{
    int temp, nHat = 0, b = 0x8000, bshft = 15;
    do
     {
        if (n >= (temp = (((nHat<<1)+b)<<bshft--)))
         {
             nHat += b;
             n -= temp;
         }
     } while (b >>= 1);
    return nHat;
}

5.建表+牛顿迭代,这个算法号称是要用来替代java数学包中的(int)(java.lang.Math.sqrt(integer))函数的,速度奇快,首先建立了一张强大的表来确定初值,然后最多经过两次牛顿迭代后就得到精确解。

inline int javaIntSqrt(int n)
{
    static int table[256] = {
        0,    16,  22,  27,  32,  35,  39,  42,  45,  48,  50,  53,  55,  57,
        59,   61,  64,  65,  67,  69,  71,  73,  75,  76,  78,  80,  81,  83,
        84,   86,  87,  89,  90,  91,  93,  94,  96,  97,  98,  99, 101, 102,
        103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118,
        119, 120, 121, 122, 123, 124, 125, 126, 128, 128, 129, 130, 131, 132,
        133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145,
        146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, 156, 157,
        158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168,
        169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178,
        179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188,
        189, 189, 190, 191, 192, 192, 193, 193, 194, 195, 195, 196, 197, 197,
        198, 199, 199, 200, 201, 201, 202, 203, 203, 204, 204, 205, 206, 206,
        207, 208, 208, 209, 209, 210, 211, 211, 212, 212, 213, 214, 214, 215,
        215, 216, 217, 217, 218, 218, 219, 219, 220, 221, 221, 222, 222, 223,
        224, 224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230, 230, 231,
        231, 232, 232, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238,
        239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246,
        246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253,
        253, 254, 254, 255
     };

    int xn;
    if (n >= 0x7FFEA810) return 0xB504;
    if (n >= 0x10000) {
        if (n >= 0x1000000) {
            if (n >= 0x10000000) {
                if (n >= 0x40000000) {
                     xn = table[n>> 24] << 8;
                 } else {
                     xn = table[n>> 22] << 7;
                 }
             } else {
                if (n>= 0x4000000) {
                     xn = table[n>> 20] << 6;
                 } else {
                     xn = table[n>> 18] << 5;
                 }
             }

             xn = (xn + 1 + (n/ xn)) >> 1;
             xn = (xn + 1 + (n/ xn)) >> 1;
            return ((xn * xn) > n) ? --xn : xn;
         } else {
            if (n>= 0x100000) {
                if (n>= 0x400000) {
                     xn = table[n>> 16] << 4;
                 } else {
                     xn = table[n>> 14] << 3;
                 }
             } else {
                if (n>= 0x40000) {
                     xn = table[n>> 12] << 2;
                 } else {
                     xn = table[n>> 10] << 1;
                 }
             }

             xn = (xn + 1 + (n/ xn)) >> 1;
            return ((xn * xn) > n) ? --xn : xn;
         }
     } else {
        if (n>= 0x100) {
            if (n>= 0x1000) {
                if (n>= 0x4000) {
                     xn = (table[n>> 8]) + 1;
                 } else {
                     xn = (table[n>> 6] >> 1) + 1;
                 }
             } else {
                if (n>= 0x400) {
                     xn = (table[n>> 4] >> 2) + 1;
                 } else {
                     xn = (table[n>> 2] >> 3) + 1;
                 }
             }
            return ((xn * xn) > n) ? --xn : xn;
         } else {
            if (n>= 0) {
                return table[n] >> 4;
             }
         }
     }
    return -1;
}

依次计算从1到1000000的每个数的整数平方根,下面分别是上面6个算法所用的时间:

0. 利用标准库sqrtl, directSqrt : 610 ms
1. 线性搜索, linearSqrt : 81256 ms
2. 二分法, bisectionSqrt : 2734 ms
3. 牛顿迭代法, newtonSqrt : 691 ms
4. 逐位确定法, fastIntSqrt : 301 ms
5. 建表+牛顿迭代, javaIntSqrt : 150 ms

可见牛顿迭代法与利用标准库sqrtl的方法速度相当,逐位确定法的速度大概是牛顿迭代法的两倍。当然,最快的还是建表+牛顿迭代,看来以其来替代(int)(java.lang.Math.sqrt(integer))也不是没有道理的。另,以上测试数据相对来说都比较小,可以想象,若是计算接近于2^31这样的大数的整数平方根,逐位确定法和建表+牛顿迭代应该更占据优势。

posted @ 2009-11-09 12:22  atyuwen  阅读(6220)  评论(2编辑  收藏  举报