by edw519 · 16y ago · 0 comments
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 :-) ]
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.