Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math pow alternative in java

Tags:

java

binary

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.

like image 245
IUnknown Avatar asked Jan 17 '26 07:01

IUnknown


1 Answers

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

like image 77
torquestomp Avatar answered Jan 19 '26 20:01

torquestomp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!