Earlier quoted context omitted.
[deleted]
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.
Ten Ways to Check if an Integer Is a Power Of Two in C
11–20 of 82 posts
[deleted]
Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#12Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#13Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#14I think it would be better to list the worst- and average-case asymptotic analyses of each method, rather than just the run-times. For instance, the "Decimal-Based Approaches to Checking for Powers of Two" will take longer depending on the size of your number.
Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#15Recent 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.
Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#16Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#17Earlier quoted context omitted.
[deleted]
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.
Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#18Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#19One they missed: (x & -x) == x
That was #9:
int isPowerOfTwo (unsigned int x)
{
return ((x != 0) && !(x & (x - 1)));
}Re: Ten Ways to Check if an Integer Is a Power Of Two in C
#20One they missed: (x & -x) == x
This is method 10 in the article, since -x is equivalent to ~x+1.