2的128次方 java,Java指数误差为2 ^ 31次幂

本文探讨了一位开发者在使用Java编写程序输出2的幂时遇到的问题,当指数超过31和32时结果异常。作者提出解决方案,指出32位整型无法表示超出范围的数值,并推荐使用long或BigInteger处理,同时介绍了利用CPU的位移操作来提高效率。
摘要由CSDN通过智能技术生成

I am writing a java program to output exponential powers of 2 (by the way, I cannot use Math.pow()), however at 2^31 and 2^32 I get something else. Also, I don't intend to accept negative integers.

My code:

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

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

output *= 2;

return output;

}

}

The output I get is:

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

解决方案

An int is represented with 32 bits. Thus any value between -2^31 and 2^31-1 can be represented. Nothing out of this range.

You can use a long (64 bits), or a BigInteger (a datastructures that can represented all numbers up to the memory limit).

The disadvantage of using these structures (especially BigInteger) is that a CPU does not always offer instructions for arithmetic. Thus adding two BigInteger instances requires more time than doing this with an int or long. In case of a long, if the CPU is 32-bit, it requires at least two instructions to process this.

On a sidenote. A CPU offers a better way to calculate the powers of two: shift operations.

You can simply write:

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

This works as follow: a shift moves bits to the left. Thus if the original value is:

0001 1011 << 2

= 0110 1100

Shifting to the left in a binary representation is arithmetically the same as multiplying with two.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值