IUnknown
IUnknown

Reputation: 9809

Math pow alternative in java

I have a need to sum up power of 2 from any digit x to 0. If x=6,desired sum is 2pow6+2pow5+.....1. While I can always write a algorithm to wind down to 0 using Math.pow - this function seems notorious performance-wise in a loop. Would appreciate if someone could help achieving the same using shift binary operators - I hear they are much more efficient than pow.

Upvotes: 2

Views: 2006

Answers (2)

torquestomp
torquestomp

Reputation: 3344

2^n + 2^(n-1) + 2^(n-2) + ... + 2 + 1 = (2^(n+1) - 1) = ((1 << (n+1)) - 1)

Upvotes: 11

piokuc
piokuc

Reputation: 26184

You don't have to calculate it in a loop, what you are trying to compute is equivalent to

Math.pow(2, x+1) - 1

Even better, you can calculate it like torquestomp suggested, which will be faster:

(1 << (x + 1)) - 1

Upvotes: 6

Related Questions