Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify this expression

Tags:

c++

c

expression

Let a, b be positive integers with different values. Is there any way to simplify these expressions:

bool foo(unsigned a, unsigned b)
{
    if (a % 2 == 0)
      return (b % 2) ^ (a < b); // Should I write "!=" instead of "^" ?
    else      
      return ! ( (b % 2) ^ (a < b) ); // Should I write "(b % 2) == (a < b)"? 
}

I am interpreting the returned value as a boolean.


1 Answers

How is it different from

 (a%2)^(b%2)^(a<b)

which in turn is

 ((a^b)&1)^(a<b)

or, indeed

 ((a ^ b) & 1) != (a < b)

Edited to add: Thinking about it some more, this is just the xor of the first and last bits of (a-b) (if you use 2's complement), so there is probably a machine-specific ASM sequence which is faster, involving a rotate instruction.

like image 70
rici Avatar answered Jul 01 '26 18:07

rici



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!