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
It's impossible using only the logical operators && and ||.
In any expression involving only && and ||, you can replace the value 0x01 (which is odd) with 0x10 (which is even), and the result will be the same because both values are logically "true" as far as the logical operators are concerned. Hence, the expression does not discriminate between the two.
If you need to prove it formally, you can do it by strong induction using the fact that any expression involving only those two operators, and which contains n operators in total, is necessarily equivalent to an expression of form either (A) && (B) or (A) || (B), where A and B are expressions involving only those two operators and which contain fewer than n operators in total. Proving the base case with n == 1 is simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With