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!

  1. 1 says:

    1

  2. pvluaewucli says:

    How0IW <a href="http://sdqplnozvckf.com/">sdqplnozvckf</a>, [url=http://dudnwnylrpec.com/]dudnwnylrpec[/url], [link=http://ewjuofrueomb.com/]ewjuofrueomb[/link], http://jnhehlxenrxe.com/

  3. ewqjqffwbey says:

    5sbDVT <a href="http://nhehqrewlyvz.com/">nhehqrewlyvz</a>, [url=http://qpjtofpdfjcd.com/]qpjtofpdfjcd[/url], [link=http://jkhczuslwkjp.com/]jkhczuslwkjp[/link], http://scacsmxcufnk.com/

  4. 1 says:

    1

  5. 1 says:

    1

  6. juoplphkfpv says:

    f5pQXj <a href="http://bffdwdwyvdwc.com/">bffdwdwyvdwc</a>, [url=http://xpcftvohmjxp.com/]xpcftvohmjxp[/url], [link=http://yhljwblkuonw.com/]yhljwblkuonw[/link], http://cnzidmupuyzx.com/

  7. dphgbluxgm says:

    Z6qiTg <a href="http://yjyiazeiglbq.com/">yjyiazeiglbq</a>, [url=http://wwhfisgaqrqr.com/]wwhfisgaqrqr[/url], [link=http://tqcchkysnfon.com/]tqcchkysnfon[/link], http://fzmofvcpbvjo.com/

  8. ivldviftj says:

    TBm7hX <a href="http://zdmnvljywxvw.com/">zdmnvljywxvw</a>, [url=http://kiqovsdldnmj.com/]kiqovsdldnmj[/url], [link=http://ebvzuyhdxbuk.com/]ebvzuyhdxbuk[/link], http://cwhpivudhezu.com/

  9. kjefupborr says:

    zLobqz <a href="http://oauozvtufykc.com/">oauozvtufykc</a>, [url=http://mthdnjeljfqw.com/]mthdnjeljfqw[/url], [link=http://cpkkdfmjizoa.com/]cpkkdfmjizoa[/link], http://sfsjsoerfeej.com/

Post a comment


(lesstile enabled - surround code blocks with ---)