I am a little bit confused while I’m trying to determine if a number is even / uneven using only logical operators (||, &&).
I’m used to:
if (x%2)
printf("Number is even");
else
printf("Number is not even");
Is there any algorithm that determinates the parity of a number ? If there is, can you give me some documentation ?
Best regards,
Duluman Edi
Can you do shifting first? You can accomplish the same “bit” logic with the logical operators if you use just 1 bit, so for example:
So anything non-0
&& 1gives you 1, in this case we shiffted off all but the lowest bit, if it’s even (as above) it leaves you with 0 and0 && 1is false so"it's even"is printed. If we use an odd number:Now there’s a non-0 number there with the 1 so we’ll get
"it's odd"