Check if a numer is a power of 2 in ruby

The One imo not-so-obvious solution is:

# 0 -> false, 1->true, 2->true, 3->false ...
n.to_s(2).scan(/1/).size == 1

And why it works is an exercise for the reader πŸ˜‰

A crazy benchmark comparing different versions of power of 2 algorithms by reto
The fastest, still readable versions is:

n & (n – 1) == 0
... followed by ...
Math.log(n) / Math.log(2) % 1 == 0

5 thoughts on “Check if a numer is a power of 2 in ruby

  1. 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 πŸ™‚

  2. I have something even faster (and are hellish proud of it):

    def ispow2(n)
    n & (n – 1) == 0

    runs twice as fast as anything πŸ˜‰

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s