I usually use n(a number) % 2 to check whether it is a even or odd. Recently, I just discovered another way by using bit wise.
if(n&1)
cout<<"Odd";
else
cout<<"Even";
Is it faster than the other? Should I use it? Thank you!
I usually use n(a number) % 2 to check whether it is a even or odd. Recently, I just discovered another way by using bit wise.
if(n&1)
cout<<"Odd";
else
cout<<"Even";
Is it faster than the other? Should I use it? Thank you!
The compiler could very easily optimize either operation into the faster one, so in practice it probably makes little difference.
I ran this experiment with my gcc compiler (5.3 on ubuntu). Given this code:
#include <iostream>
int main()
{
for(int i=0; i<100; ++i) {
//if(i % 2 == 0)
if(!(i & 1))
std::cout << "i is odd" << std::endl;
else
std::cout << "i is even" << std::endl;
}
}
Whichever of the if
lines I commented out, the assembly code produced is exactly the same, namely:
mov eax, DWORD PTR [rbp-4] # D.35290, i
and eax, 1 # D.35290,
test eax, eax # D.35290
In other words the compiler produced the AND version of the comparison in both cases. This is with default optimisation.