Asia x3 - 1 year ago 68

Java Question

I am having issues with my recursive method, that will return and print in main() the sum of the powers of 2 up to the Xth power of 2. X is a integer on the commandline argument.

So if my commandline argument is : "3"

*Output would be: 15

It should work like (1 + 2 + 4 + 2^3) As you can see there's "3" powers of 2

So whatever my number is that's how much powers of 2 will be added. I manage to work out in getting the power of 2^x, but I'm really confused on getting the sum of the powers of 2 to be added into my calculation :o

Also, I won't be utilizing Math.pow(), even if it would be easier x)

My code atm:

`public static void main(String[] commandlineArguments) {`

if (commandlineArguments.length == 0) {

System.out.println("Please enter a least one commandline!");

}

else {

Integer number = new Integer(0); // initialize number

try {

number = Integer.parseInt(commandlineArguments[0]);

}

catch (NumberFormatException exception) { // NumberFormatException

System.out.println(exception + " is not a integer!");

System.exit(1); // end program

}

Integer power = power2(number);

System.out.println(power);

}

}

public static Integer power2(Integer number){

if (number == 0) {

return 1;

}

else {

return 2 * power2(number - 1);

}

}

}

Answer Source

First of all stick with the `int`

rather that Integer as primitives are much faster and introduce less overhead.

Secondly, if you only need the powers of 2 I suggest using left shift operator, `<<`

as it does just what you need:

```
public static int powerOf2Sum(int number) {
if( number == 0 ) {
return 1;
}
return (1 << number) + powerOf2Sum( number - 1 );
}
```

Note: be aware of integer overflow though, as when the power is great than 32 (the number of bits in int) it will roll over. In that case you would need a long, which is capable of representing integers up to 64's power.