Brian Ewing
Ruby Fixnum#power_of?
This is my quick solution:
Gotta love Ruby. I’ve seen others solve this iteratively/recursively dividing by i until less than or equal to i. Less than meaning not a power, and equal to meaning it is a power. This is an expensive operation, whereas this uses the magic of logarithms.
One problem is with the check at the end (whether the exponent of i is a whole number by checking if it’s exactly divisible by 1) failing. Floating point precision means that there will be a remainder of ~0.000000001, and it’ll give a false negative. This happens above 2^29, unfortunately. This could be ""fix’d"" by checking if the remainder is <= 0.000000001, but that’s a bit of a hack.
This is the best implementation I can come up with right now though. I’ve seen a great implementation for powers of two, like this:
1 2 3 |
def power_of_two?(i) i >= 0 and i & (i - 1) == 0 end |
Which, unfortunately, won’t work for bases other than 2. Feel free to improve my Gist above!




