The One imo not-so-obvious solution is:
And why it works is an exercise for the reader π
Update:
A crazy benchmark comparing different versions of power of 2 algorithms by reto
The fastest, still readable versions is:
The One imo not-so-obvious solution is:
And why it works is an exercise for the reader π
Update:
A crazy benchmark comparing different versions of power of 2 algorithms by reto
The fastest, still readable versions is:
arggh π
Math.log(n)/Math.log(2) % 1 == 0
=> does not convert a number to a binary string representation
=> does not compile a regexp
=> does not create a array of 1’s
=> does not count them π
probably something with bit arithmetic is still faster than the log π
or what about
n.to_s(2).match(/^10*$/)
π
I have something even faster (and are hellish proud of it):
def ispow2(n)
n & (n – 1) == 0
end
runs twice as fast as anything π
Wow, actually readable and fast, its not very intuitive, but makes sense when you think about it π
(0..n).map {|i|n[i]}.inject(:+) == 1
That’s a somewhat obscure and fairly inefficient way to do it.