Thursday, August 28, 2008

How to find greatest of two/three/four numbers without using relational operators ?

Finding greatest of two numbers:

  • int maxof2(int a,int b)
    {
    return (a + b + abs(a - b))/2;
    }


  • /****************************************************
    Purpuse : Evaluate the bigger one of two integers.
    Author : ALNG
    Date : 2003-03-11
    Original : http://search.csdn.net/Expert/topic/1515/1515035.xml
    **************************************************/


    inline int signof(int i)
    {
    return unsigned(i) >> (sizeof (int) * 8 - 1);
    }

    int max(int a, int b)
    {
    int p[2];
    p[0] = a;
    p[1] = b;

    return p[signof(a - b)];
    }

Function for finding greatest of three numbers:
int maxof3(int a, int b, int c)
{
return (a + b + c * 2 + abs(a - b) + abs(a + b - c * 2 + abs(a - b))) / 4;
}


Function for finding greatest of four numbers:
int maxof4(int a, int b, int c, int d)
{
return (a + b + c + d + abs (b - a) + abs(d - c) + abs(a + b - c - d + abs( b - a) - abs(d - c)))/ 4;
}



Warning: These functions might invoke undefined behavior when it overflows/underflows the integer value in the expression, so better not use these methods in actual applications, just use the relational/comparison operators.

0 comments: