On Dec 6, 9:33 pm, (E-Mail Removed) wrote:

> Hi all,

>

> The following question is asked frequently in interviews

>

> How to find the greatest of 2 numbers without using relational

> operators ?

>

> the solution i have seen is

>

> ( a+b + abs(a-b) ) /2 ;

>

> is there any better solution than this ....?????
I think it is moronic to ask for gag answers in an interview. I

imagine that they were looking for the solutions from this web site:

http://aggregate.org/MAGIC/
--------------------------------------------------------------------------------

Integer Minimum or Maximum

Given 2's complement integer values x and y, the minimum can be

computed without any branches as x+(((y-x)>>(WORDBITS-1))&(y-x)).

Logically, this works because the shift by (WORDBITS-1) replicates the

sign bit to create a mask -- be aware, however, that the C language

does not require that shifts are signed even if their operands are

signed, so there is a potential portability problem. Additionally, one

might think that a shift by any number greater than or equal to

WORDBITS would have the same effect, but many instruction sets have

shifts that behave strangely when such shift distances are specified.

Of course, maximum can be computed using the same trick: x-(((x-

y)>>(WORDBITS-1))&(x-y)).

Actually, the Integer Selection coding trick is just as efficient in

encoding minimum and maximum....

--------------------------------------------------------------------------------

Integer Selection

A branchless, lookup-free, alternative to code like if (a<b) x=c; else

x=d; is ((((a-b) >> (WORDBITS-1)) & (c^d)) ^ d). This code assumes

that the shift is signed, which, of course, C does not promise.

--------------------------------------------------------------------------------

Writing weird crap like that when you mean:

maxab = a > b ? a : b;

is just plain stupid. Since 80% of the cost of software is

maintenance, writing code that is hard to maintain is counter

productive.

Now, in the very rare case, where you have some deeply nested loop and

a comparison is slowing the code down, then you can do a quick web

search and find simple gag solutions like the above. You will notice

that these gag solutions have caveats in them, so they would have to

be both heavily tested and also heavily commented.

Chances are good that profile guided optimization of the simple

solution will work just as well, since the right branch will be

predicted most of the time.