

A faster next-power-of-two algorithm - peripetylabs
http://www.eliteraspberries.com/blog/2013/05/a-faster-next-power-of-two-algorithm.html

======
ColinWright
I'm confused by this. Both the algorithms mentioned seem to give the wrong
result when N is a power of 2.

For example, N=4. Set all the lower bits to 1, giving 7. Increment, giving 8,
return 8. But the power of two no less than 4 is 4.

Am I missing something?

Also, the alleged faster solution is only faster for larger numbers (on a log
scale). Sure, there are more of them, but what if your function is called more
often for small numbers than large ones?

~~~
peripetylabs
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_...](http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two)

(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.

~~~
ColinWright

       > ... 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.

