今天我需要一个简单的算法来检查一个数字是否是2的幂。

该算法需要:

简单的 适用于任何ulong值。

我想出了这个简单的算法:

private bool IsPowerOfTwo(ulong number)
{
    if (number == 0)
        return false;

    for (ulong power = 1; power > 0; power = power << 1)
    {
        // This for loop used shifting for powers of 2, meaning
        // that the value will become 0 after the last shift
        // (from binary 1000...0000 to 0000...0000) then, the 'for'
        // loop will break out.

        if (power == number)
            return true;
        if (power > number)
            return false;
    }
    return false;
}

但后来我想:如何检查log2x是否恰好是一个整数呢?当我检查2^63+1时,Math.Log()因为四舍五入而返回恰好63。我检查了2的63次方是否等于原来的数,结果是正确的,因为计算是双倍的,而不是精确的数字。

private bool IsPowerOfTwo_2(ulong number)
{
    double log = Math.Log(number, 2);
    double pow = Math.Pow(2, Math.Round(log));
    return pow == number;
}

这对于给定的错误值返回true: 9223372036854775809。

有没有更好的算法?


当前回答

在C中,我测试了I && !(I & (I - 1)技巧,并将其与__builtin_popcount(I)进行比较,在Linux上使用gcc,使用-mpopcnt标志,以确保使用CPU的POPCNT指令。我的测试程序计算了0到2^31之间2的幂的整数个数。

起初,我认为I && !(I & (I - 1)快10%,即使我验证了在我使用__builtin_popcount的反汇编中使用了POPCNT。

然而,我意识到我已经包含了一个if语句,分支预测可能在位旋转版本上做得更好。我删除了if和POPCNT,结果更快,正如预期的那样。

结果:

英特尔(R)酷睿(TM) i7-4771 CPU最大3.90GHz

Timing (i & !(i & (i - 1))) trick
30

real    0m13.804s
user    0m13.799s
sys     0m0.000s

Timing POPCNT
30

real    0m11.916s
user    0m11.916s
sys     0m0.000s

AMD Ryzen Threadripper 2950X 16核处理器最大3.50GHz

Timing (i && !(i & (i - 1))) trick
30

real    0m13.675s
user    0m13.673s
sys 0m0.000s

Timing POPCNT
30

real    0m13.156s
user    0m13.153s
sys 0m0.000s

请注意,这里英特尔的CPU似乎比AMD的比特旋转稍慢,但有一个更快的POPCNT;AMD的POPCNT没有提供这么多的提升。

popcnt_test.c:

#include "stdio.h"

// Count # of integers that are powers of 2 up to 2^31;
int main() {
  int n;
  for (int z = 0; z < 20; z++){
      n = 0;
      for (unsigned long i = 0; i < 1<<30; i++) {
       #ifdef USE_POPCNT
        n += (__builtin_popcount(i)==1); // Was: if (__builtin_popcount(i) == 1) n++;
       #else
        n += (i && !(i & (i - 1)));  // Was: if (i && !(i & (i - 1))) n++;
       #endif
      }
  }

  printf("%d\n", n);
  return 0;
}

运行测试:

gcc popcnt_test.c -O3 -o test.exe
gcc popcnt_test.c -O3 -DUSE_POPCNT -mpopcnt -o test-popcnt.exe

echo "Timing (i && !(i & (i - 1))) trick"
time ./test.exe

echo
echo "Timing POPCNT"
time ./test-opt.exe

其他回答

对于2的任意次幂,也成立。

n& (-n) = = n

注意:n=0失败,需要检查 这样做的原因是: -n是n的2s补。-n将使n的最右集合位左边的每一位与n相比翻转。对于2的幂,只有一个集合位。

我一直在看《兰登》的文档。nextInt(int bound),看到了这段漂亮的代码,它检查参数是否为2的幂,它说(代码的一部分):

if ((bound & -bound) == bound) // ie, bouns is a power of 2   

我们来测试一下

for (int i=0; i<=8; i++) {
  System.out.println(i+" = " + Integer.toBinaryString(i));
}

>>
0 = 0
1 = 1
2 = 10
3 = 11
4 = 100
5 = 101
6 = 110
7 = 111
8 = 1000
// the left most 0 bits where cut out of the output

for (int i=-1; i>=-8; i--) {
  System.out.println(i+" = " + Integer.toBinaryString(i));
}

>>
-1 = 11111111111111111111111111111111
-2 = 11111111111111111111111111111110
-3 = 11111111111111111111111111111101
-4 = 11111111111111111111111111111100
-5 = 11111111111111111111111111111011
-6 = 11111111111111111111111111111010
-7 = 11111111111111111111111111111001
-8 = 11111111111111111111111111111000

你注意到什么了吗? 2次方的数字在正负二进制表示中有相同的位,如果我们做一个逻辑与,我们得到相同的数字:)

for (int i=0; i<=8; i++) {
  System.out.println(i + " & " + (-i)+" = " + (i & (-i)));
}

>>
0 & 0 = 0
1 & -1 = 1
2 & -2 = 2
3 & -3 = 1
4 & -4 = 4
5 & -5 = 1
6 & -6 = 2
7 & -7 = 1
8 & -8 = 8

假设1是2的幂,也就是2的0次方

 bool IsPowerOfTwo(ulong testValue)
 {
  ulong bitTest = 1;
  while (bitTest != 0)
  {
    if (bitTest == testValue) return true;
    bitTest = bitTest << 1;
  }

  return false;
}

如果该数字是2的幂到64的值,则返回该值(您可以在for循环条件中更改它(“6”表示2^6 = 64);

const isPowerOfTwo = (number) => { 让结果= false; For(令I = 1;I <= 6;我+ +){ if (number ===数学。Pow (2, i)) { 结果= true; } } 返回结果; }; console.log (isPowerOfTwo (16)); console.log (isPowerOfTwo (10));

我看到很多答案都建议返回n && !(n & (n - 1)),但根据我的经验,如果输入值为负,它会返回假值。 我将在这里分享另一种简单的方法,因为我们知道2的幂数只有一个集位,所以简单地,我们将计算集位的数量,这将花费O(log N)时间。

while (n > 0) {
    int count = 0;
    n = n & (n - 1);
    count++;
}
return count == 1;

检查这篇文章数不清。固定位的