Write a C program to find the smallest of three integers, without using any of the comparison operators.
Method 2 (Use Bit Operations)
Method 3 (Use Division operator)
We can also use division operator to find minimum of two numbers. If value of (a/b) is zero, then b is greater than a, else a is greater.
Read full article from Smallest of three integers without comparison operators | GeeksforGeeks
Method 2 (Use Bit Operations)
int
min(
int
x,
int
y)
{
return
y + ((x - y) & ((x - y) >>
(
sizeof
(
int
) * CHAR_BIT - 1)));
}
/* Function to find minimum of 3 numbers x, y and z*/
int
smallest(
int
x,
int
y,
int
z)
{
return
min(x, min(y, z));
}
We can also use division operator to find minimum of two numbers. If value of (a/b) is zero, then b is greater than a, else a is greater.
int
smallest(
int
x,
int
y,
int
z)
{
if
(!(y/x))
// Same as "if (y < x)"
return
(!(y/z))? y : z;
return
(!(x/z))? x : z;
}