Reputation: 316
I'm doing a project where I need the code to be able to determine if input is odd or not. (I also need to be able to determine if it is even
Can you explain what this means? Mainly the first part.
if((x & 1) == 0)
printf("EVEN!\n");
else
printf("ODD!\n");
Upvotes: 2
Views: 217
Reputation: 1080
It's a bitwise operation. The AND operation masks every bit and leave the last one. If the last bit is off (you're checking against zero), means it's even otherwise means it's odd.
An example:
125 in binary form is 01111101
so
01111101 AND
00000001 =
------------
00000001
so 125 is ODD :)
An alternative way to check even or odd is to use the module of division:
if (x % 2 == 0) printf("EVEN");
else printf("ODD");
As noted by a user in a comment below, this second solution is slower (in terms of μS)
Upvotes: 8
Reputation: 8753
A simpler way to do it would be to:
if( x % 2 == 0 )
{
printf("EVEN!\n");
}
else
{
printf("ODD!\n");
}
The %, or modulus operator, returns the remainder.
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
Upvotes: 0
Reputation: 444
As stated in the other answer it is a bitwise operation, but the test is actually if the last bit is set it is ODD, hence the ==0
. So if the last bit is NOT set it is EVEN.
EDIT: Just saw that answer was deleted, oh well.
Upvotes: 2