I know this method and it is not efficient enough
(a/2)%2==0;
I know this method and it is not efficient enough
(a/2)%2==0;
See the Bit Twiddling Hacks :
unsigned int v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v & (v - 1)) == 0;
Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
f = v && !(v & (v - 1));
Your method does not check that. It will return true for 12 for example.(and will return false for 2)
To check you may use x != 0 && (x & (x - 1)) == 0
If you're using gcc and x64 there's an intrinsic that lets you use the CPU instruction that counts bits:
int __builtin_popcount (unsigned int x)