How do you find the biggest of two numbers with minimal instruction.
Answers
On some rare machines where branching is expensive, the below obvious approach to find minimum can be slow as it uses branching.
/* The obvious approach to find minimum (involves branching) */
int min(int x, int y)
{
return (x < y) ? x : y
}
Below are the methods to get minimum(or maximum) without using branching. Typically, the obvious approach is best, though.
Method 1(Use XOR and comparison operator)
Minimum of x and y will be
y ^ ((x ^ y) & -(x < y))
It works because if x < y, then -(x = y, then -(x < y) will be all zeros, so r = y ^ ((x ^ y) & 0) = y. On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, so there may be no advantage.
To find the maximum, use
x ^ ((x ^ y) & -(x < y));
// C++ program to Compute the minimum
// or maximum of two integers without
// branching
#include<iostream>
using namespace std;
class gfg
{
/*Function to find minimum of x and y*/
public:
int min(int x, int y)
{
return y ^ ((x ^ y) & -(x < y));
}
/*Function to find maximum of x and y*/
int max(int x, int y)
{
return x ^ ((x ^ y) & -(x < y));
}
};
/* Driver code */
int main()
{
gfg g;
int x = 15;
int y = 6;
cout << "Minimum of " << x <<
" and " << y << " is ";
cout << g. min(x, y);
cout << "\nMaximum of " << x <<
" and " << y << " is ";
cout << g.max(x, y);
getchar();
}
// This code is contributed by
Output
Minimum 15 and 6 is 6
Maximum 15and 6 is 15