Pages

Monday, December 5, 2011

A quick way to sum powers of 2

A lot of development tasks involve working with powers of 2. For example, you may use enum declarations with powers of 2 in your server-side code, store data on the server in binary format, or keep track of user choices by assigning different powers of 2 to your HTML form elements.

If you ever need to sum the powers of 2 up to a certain power (e.g., to calculate the highest possible combination of enum values), here's a quick shortcut for you: Just take the next power of 2 and subtract 1. For example, to sum the powers of 2 up to 2-to-the-4th, you could program a loop to do 1 + 2 + 4 + 8 + 16 = 31. But the easier way is to just add 1 to your power to get 2-to-the-5th = 32 and subtract 1 to get 31. You can easily prove this by induction since (2 to the x+1) times 2 is (2 to the x+2).

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.