News for hackers. Stuff that matters.
Re:Write A Function To Determine If A Number Is A Power Of 2 by edw519 on Monday October 18, 2010 @12:20PM (#1804053)
1990: a junior programmer who doesn't know any better:

  IF NOT(MOD(X,2)) THEN...
2000: a senior programmer, using OP's slick bit flipping approach:

  def power_of_2?(number)
   number != 0 && number & (number - 1) == 0
  end
2010: either a master or a lazy programmer, having pity on whoever has to maintain it:

  if !(mod(x,2)) then ...
Now that clock speeds are so much faster, can we all just go back to being lazy and focus on the real problem at hand?

[EDIT: Oops, I confused "power of 2" with "divisible by 2", rendering my entire comment stupid and pointless. But I won't delete it because so much is hanging below it already. This is a perfect example of what we hackers can never allow ourselves to do: wave our hands at the trees because we're so busy looking at the forest. I promise I won't do this again, at least until tomorrow. Now I'm going to close my browser and get back to work :-) ]

Re:Write A Function To Determine If A Number Is A Power Of 2 by yan on Monday October 18, 2010 @12:26PM (#1804085)
I don't think a function named 'power_of_2?' can be any less clear about what it does regardless of its implementation. There are ways we can keep the different forces happily balanced (intellectual gratification, clarity, well-placed verbosity and maintainability)
Re:Write A Function To Determine If A Number Is A Power Of 2 by sad on Monday October 18, 2010 @12:26PM (#1804082)
Yes, but we must solve the problems correctly. The question is whether a number is a power of two, not divisible by 2.
Re:Write A Function To Determine If A Number Is A Power Of 2 by yan on Monday October 18, 2010 @12:27PM (#1804088)
I think Ed wrote the first line of a function, not all of it. See the iterative solution in the posted article.
Re:Write A Function To Determine If A Number Is A Power Of 2 by sad on Monday October 18, 2010 @12:31PM (#1804107)
Ohh, looks like you are probably right. Mea culpa!
Re:Write A Function To Determine If A Number Is A Power Of 2 by nevinera on Monday October 18, 2010 @12:24PM (#1804073)
mod(x,2) will tell you that it's even, not that it's a power of two.
Re:Write A Function To Determine If A Number Is A Power Of 2 by Retric on Monday October 18, 2010 @12:41PM (#1804157)
I think his first example was a recursive function like:

  if !(mod(x,2) {
   if (x == 1) return true  else return false;
  }else return is_power_of_2(x/2);
or

  if !(mod(x,2) {
   if (x == 1) return true;
   if ((x > 1) || (x == 0)) return false;
   return is_power_of_2(x * 2);
  }else if (x > 2) return is_power_of_2(x/2) else return false;
PS: 2^0 = 1 and 2^-1 so you could have 3 versions of this fuction.
Re:Write A Function To Determine If A Number Is A Power Of 2 by mfukar on Monday October 18, 2010 @12:30PM (#1804102)
Lazy programmer it is!