Friday, April 13, 2007

Greater of two numbers

I come across many programming puzzles. So I have decided to collect most of them at this place. Hope you like the puzzles. I start with a simple puzzle which is asked in many IT companies as an interview question.

Is there any way of finding the greater of two numbers without using any logical operators?

Yeah there is. It's pretty straight forward:

max(a,b) = 1/2(a+b + abs(a-b)); abs(x) being the absolute value of x.

That's because,

If a > b, 1/2(a+b + a-b) = a.

If b > a, 1/2(a+b + b-a) = b.

Another one I can think of is the following - though it involves the use of an if block:

if(abs(a-b)-(a-b))
{
  //Code of a < b follows
}
else
{
  //Code of a >= b follows
}

Please suggest any others you can think of.