top | item 5692300

(no title)

peripetylabs | 12 years ago

To me, the next power of two after 4 is 8, not 4. If you prefer, you can add a line to simply return the input if it is already a power of two:

http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_...

(Edit: You forgot to subtract one before setting the lower bits and incrementing. If you omit that step, both these algorithms give the same result.)

Actually this algorithm is faster for smaller numbers too, because it always performs less operations in the loop -- one shift as opposed to a shift and a bitwise or.

discuss

order

ColinWright|12 years ago

   > ... the next power of two after 4 is 8, not 4
But he says the power of two not less than N. That's not the next power of two that's strictly greater than N.