Friday, May 30, 2008

Max of two integers

Max of two integers without using any conditional operators.
-b)

Solution 1:
===========
max = (a + b + absolute(a - b))/2

If a > b then max = (a + b + a - b)/2 = 2*a/2 = a
otherwise a < b then max = (a + b + b - a)/2 = 2*b/2 = b


Solution 2:
===========
max = b*(((a-b)& 0x8000)>>32) + a*(((b-a)& 0x8000)>>32)

3 comments:

Ashish Shukla said...
This comment has been removed by the author.
Ghotter said...

I am sorry to say i dont understand your language... So if you can post your comments in english it would be great...

aravind sen said...

max = b*(((a-b)& 0x80)>>7) + a*(((b-a)& 0x80)>>7)
this works for me

superb.. algo infact.. by the author