Java指数误差为2 ^ 31次幂

我正在编写一个java程序来输出2的指数幂(顺便说一句,我不能使用Math.pow() ),但是在2 ^ 31和2 ^ 32我得到了别的东西。 另外,我不打算接受负整数。

我的代码:

 class PrintPowersOf2 { public static void main (String[] args) { printPowersOf2(10); printPowersOf2(5); printPowersOf2(2); printPowersOf2(-5); printPowersOf2(30); printPowersOf2(32); } public static void printPowersOf2 (int x) { for(int i=0;i<x+1;i++) { int y = exponent (i); System.out.print(y); if(!(i == x)) { System.out.print(" "); } } System.out.println(); } static int exponent(int power) { int output = 1; for (int z=0; z<power; z++) output *= 2; return output; } } 

我得到的输出是:

 1 2 4 8 16 32 64 128 256 512 1024 1 2 4 8 16 32 1 2 4 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648 0 

int用32位表示。 因此,可以表示-2^312^31-1之间的任何值。 没有超出这个范围。

您可以使用long (64位)或BigInteger (可以表示所有数字达到内存限制的数据结构)。

使用这些结构(尤其是BigInteger )的缺点是CPU并不总是提供算术指令。 因此,添加两个BigInteger实例比使用intlong执行此操作需要更多时间。 如果long ,如果CPU是32位,则至少需要两条指令来处理它。


在旁注。 CPU提供了一种更好的方法来计算两种function:移位操作。

你可以简单地写:

 long value = 0x01L << power;//power of two, all in one simple instruction. 

其工作原理如下:移位向左移动位。 因此,如果原始值是:

  0001 1011 << 2 = 0110 1100 

以二进制表示向左移位在算术上与乘以2相同。

一般来说,

 byte 8 bits, short 16 bits, int 32 bits, long 64 bits 

对于Integer(int),您可以存储介于-2 ^ 31和2 ^ 31之间的值,即-2,147,483,648到2,147,483,647之间的值

如果你真的想要计算2的幂而没有任何限制(至少根据理论),你可以使用字符串并相应地进行乘法运算。

编辑

正如Commusoft所建议的那样,BigIntegers也可以用来提高性能而不是字符串。