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!





July 04, 2012 at 2:20 PM
1
November 04, 2012 at 6:31 PM
How0IW <a href="http://sdqplnozvckf.com/">sdqplnozvckf</a>, [url=http://dudnwnylrpec.com/]dudnwnylrpec[/url], [link=http://ewjuofrueomb.com/]ewjuofrueomb[/link], http://jnhehlxenrxe.com/
March 20, 2013 at 12:00 PM
5sbDVT <a href="http://nhehqrewlyvz.com/">nhehqrewlyvz</a>, [url=http://qpjtofpdfjcd.com/]qpjtofpdfjcd[/url], [link=http://jkhczuslwkjp.com/]jkhczuslwkjp[/link], http://scacsmxcufnk.com/
June 08, 2012 at 2:29 PM
1
June 22, 2012 at 6:25 PM
1
October 06, 2012 at 8:23 PM
f5pQXj <a href="http://bffdwdwyvdwc.com/">bffdwdwyvdwc</a>, [url=http://xpcftvohmjxp.com/]xpcftvohmjxp[/url], [link=http://yhljwblkuonw.com/]yhljwblkuonw[/link], http://cnzidmupuyzx.com/
November 16, 2012 at 8:11 AM
Z6qiTg <a href="http://yjyiazeiglbq.com/">yjyiazeiglbq</a>, [url=http://wwhfisgaqrqr.com/]wwhfisgaqrqr[/url], [link=http://tqcchkysnfon.com/]tqcchkysnfon[/link], http://fzmofvcpbvjo.com/
March 29, 2013 at 7:50 PM
TBm7hX <a href="http://zdmnvljywxvw.com/">zdmnvljywxvw</a>, [url=http://kiqovsdldnmj.com/]kiqovsdldnmj[/url], [link=http://ebvzuyhdxbuk.com/]ebvzuyhdxbuk[/link], http://cwhpivudhezu.com/
April 25, 2013 at 5:22 PM
zLobqz <a href="http://oauozvtufykc.com/">oauozvtufykc</a>, [url=http://mthdnjeljfqw.com/]mthdnjeljfqw[/url], [link=http://cpkkdfmjizoa.com/]cpkkdfmjizoa[/link], http://sfsjsoerfeej.com/