# To find a>b or a<b without using of Logical & relational Operators!!!

Discussion in 'C' started by asadullah.ansari, Jan 12, 2008.

Joined:
Jan 9, 2008
Messages:
356
14
Trophy Points:
0
Occupation:
Developer
Location:
NOIDA
Program to find max(x,y) or Min(x,y) without using any relational and logical operator.

Code:
```int maximum(int x, int y)
{
int fNum[2],temp,num[2];
num[0] = x;
num[1] = y;
temp=fNum[ Fun4Sign(x - y)];
return( temp);
}

int Fun4Sign(int sgn)
{
int temp;
temp= unsigned(sgn) >>  (sizeof(int)*8-1);    return(temp);
}```
EXTRA DOSE: One More thing to find min and max...
Code:
```int  MinimumOf( int a, int b)
{
return(   b + ((a - b) & ((a - b) >> (sizeof(int) * CHAR_BIT - 1)))  );
}```
Code:
```int  MaximumOf( int a, int b)
{
return(   a - ((a - b) & ((a - b) >> (sizeof(int) * CHAR_BIT - 1)))  );
}```

Joined:
Jul 12, 2004
Messages:
15,326
377
Trophy Points:
83
Looks like there is some problem in your code where you have not defined num

3. ### oogaboogaNew Member

Joined:
Jan 9, 2008
Messages:
115
11
Trophy Points:
0
That's pretty neat, the perhaps not universally portable.
Your code does better than just avoiding relational and logical operators,
it also avoids conditional (and loop) statements (including ?: ).
Here's a re-write:
Code:
```#include <limits.h> /* for CHAR_BIT: number of bits in a char */

#define INT_BITS (sizeof(int) * CHAR_BIT)

int maximum( int x, int y ) {
int xy[] = { x, y };
return xy[ getSign( x - y )]; /* Index xy by sign of (x-y) */
}

int getSign( int n ) { /* Returns sign bit of n */
return (unsigned)n >> INT_BITS - 1;
}
```
One could replace int xy[] = { x, y } by int* xy = &x, but
that assumes (minimally) that x has a lower address than y.
the sign bit that may not work on all computers.

I also found your MinimumOf and MaximumOf interesting:
Code:
```    /* Fill n with its sign bit, becoming all 1's or 0's */
#define spread_sign(n) ((n) >> (INT_BITS - 1))

/* Return zero if n is positive, otherwise return n */

int minimumOf( int a, int b ) {
return b + zero_if_positive( a - b );
}

int maximumOf( int a, int b ) {
return a - zero_if_positive( a - b );
}
```

Joined:
Jan 9, 2008
Messages:
356
14
Trophy Points:
0
Occupation:
Developer
Location:
NOIDA

Very Very Sorry for this mistake.

correct code will be

Code: C
Code:
```int maximum(int x, int y)
{
int fNum[2],temp,num[2];
num[0] = x;
num[1] = y;
temp=fNum[ Fun4Sign(x - y)];
return( temp);
}

int Fun4Sign(int sgn)
{
int temp;
temp= unsigned(sgn) >>  (sizeof(int)*8-1);    return(temp);
}```

Last edited by a moderator: Jan 14, 2008