Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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 :-) ]



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)


Yes, but we must solve the problems correctly. The question is whether a number is a power of two, not divisible by 2.


I think Ed wrote the first line of a function, not all of it. See the iterative solution in the posted article.


Ohh, looks like you are probably right. Mea culpa!


mod(x,2) will tell you that it's even, not that it's a power of two.


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.


Lazy programmer it is!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: