One they missed: (x & -x) == x
It should be: ((x>0) && ((x & -x) == x))
21–30 of 82 posts
One they missed: (x & -x) == x
It should be: ((x>0) && ((x & -x) == x))
Recent Intel/AMD CPUs have a POPCNT instruction, which seems like the logical way to do this. Would be interested to see how that performs compared to these implementations.
It does seem odd that the article misses this approach out.
Earlier quoted context omitted.
Because the methods clearly get more complicated. Starting simply and naively and then improving is a perfectly standard way of teaching. Articles like these, which provide detailed explanation of the methods involved and results of benchmarks help greatly.
The benchmarks would probably be somewhat misleading in a lot of cases here. I'm fairly certain that most compilers will replace a /2 with >>1 for example, so that isn't really going to end up being reflected when you compile it.
EDIT: http://blogs.msdn.com/b/shawnhar/archive/2007/03/19/a-story-... gives other reasons why multiplications can be faster than bit shifts.
return ((x != 0) && !(x & (x - 1)));
This is beautiful. #(python code)
def is_power_of_two(n):
import math
if n return ((x != 0) && !(x & (x - 1))); This is beautiful.
It seems bizarre to call the first group of methods "decimal based" when the methods don't ever look at the decimal digits of the number being tested. I would call them "arithmetic" or something like that.