Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the parity of a number using only logical operators

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

like image 711
Eduard Avatar asked Nov 16 '25 14:11

Eduard


1 Answers

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.

like image 97
Steve Jessop Avatar answered Nov 19 '25 08:11

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!