Rick DeNatale wrote: > On 8/7/06, Simon Kröçer <SimonKroeger / gmx.de> wrote: >> Rick DeNatale wrote: > >> > My original intention was to benchmark the various suggestions, but >> > since you can get the wrong answers with arbitrarily fast code, I >> > don't think that it matters much. >> >> Hmm, what about: >> >> def next_power_of_2(n) >> throw 'eeek' if n < 0 >> return 1 if n < 2 >> 1 << (n-1).to_s(2).size >> end >> >> ? > > Ahh, but the following is both quicker and more economical of source code > > def next_power_of_2(n) > end > > If you don't care about a correct answer, then nil is as good as any. <G> would you dare to explain? def next_power_of_2(n) throw 'eeek' if n < 0 return 1 if n < 2 1 << (n-1).to_s(2).size end puts next_power_of_2(0) #=> 1 puts next_power_of_2(1) #=> 1 puts next_power_of_2(2) #=> 2 puts next_power_of_2(3) #=> 4 puts next_power_of_2(4) #=> 4 puts next_power_of_2(5) #=> 8 puts next_power_of_2(255) #=> 256 puts next_power_of_2(256) #=> 256 puts next_power_of_2(257) #=> 512 puts next_power_of_2(536870911) #=> 536870912 puts next_power_of_2(536870912) #=> 536870912 puts next_power_of_2(536870913) #=> 1073741824 seems to be correct for a lot more cases than nil(?) cheers Simon