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