From: Farrel Lifson Date: 2006-08-07T23:53:47+09:00 Subject: Re: nextPowerOf2(n) On 07/08/06, Farrel Lifson wrote: > On 07/08/06, Farrel Lifson wrote: > > On 07/08/06, Ch Skilbeck wrote: > > > Hi, > > > > > > Can someone tell me if there's a better way to do this? It takes a > > > number and returns the next power of 2 up (or the original if it was > > > already a power of 2) Specifically, are there features of Ruby that I > > > should be using in this case? > > > > > > Cheers, > > > Charlie. > > > > > > def nextPowerOf2(n) > > > raise "integer please" if !n.kind_of? Integer > > > high = 0 > > > count = 0 > > > (0..n.size * 8 - 2).each {|b| count += n[b] ; high = b if n[b] != 0} > > > 1 << high + (count > 1 ? 1 : 0) > > > end > > > > > > > > > -- > > > Posted via http://www.ruby-forum.com/. > > > > > > > > > > My attempt: > > > > # Finds the log base 2 of a number > > def Math.log2(n) > > Math.log(n)/Math.log(2) > > end > > > > def nextPowerOf2(n) > > if Math.sqrt(n).modulo(1).zero? > > n > > else > > 2**Math.log2(5).to_i.succ > > end > > end > > > > Farrel > > > > Gah! I don't even need that Math.log2 function > > def nextPowerOf2(n) > if Math.sqrt(n).modulo(1).zero? > n > else > 2**Math.sqrt(5).to_i.succ > end > end > > Farrel > Sorry for the repeated typos, it shoud be '2**Math.sqrt(n).to_i.succ'