Java exponent error at 2^31 power
java
Solution
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.
Problem
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<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; } } ``` 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 ```