How do I programmatically return the maximum of two integers without using any comparison operators and without using if
, else
, etc?
return (a > b ? a : b);
or
int max(int a, int b)
{
int x = (a - b) >> 31;
int y = ~x;
return (y & a) | (x & b);
}
not as snazzy as the above... but...
int getMax(int a, int b)
{
for(int i=0; (i<a) || (i<b); i++) { }
return i;
}
In the math world:
max(a+b) = ( (a+b) + |(a-b)| ) / 2
min(a-b) = ( (a+b) - |(a-b)| ) / 2
Apart from being mathematically correct it is not making assumptions about the bit size as shifting operations need to do.
|x|
stands for the absolute value of x.
You are right, the absolute value was forgotten. This should be valid for all a, b positive or negative
Since this is a puzzle, solution will be slightly convoluted:
let greater x y = signum (1+signum (x-y))
let max a b = (greater a b)*a + (greater b a)*b
This is Haskell, but it will be the same in any other language. C/C# folks should use "sgn" (or "sign"?) instead of signum.
Note that this will work on ints of arbitrary size and on reals as well.