Find the maximum and minimum of two integers without branching i.e. if condition.
Solution:
Minimum of two numbers can be found from the following:
Min(x,y) = y ^ ((x ^ y) & -(x < y))
It works because if x < y, then -(x < y) will be all ones, so r = y ^ (x ^ y) & ~0 = y ^ x ^ y = x. Otherwise, if 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.
Similarly the maximum of two integers can be found from the following:
Max(x,y) = x ^ ((x ^ y) & -(x < y))
#include<stdio.h> /*Function to find minimum of x and y*/ 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)); }
Is this correct way to do above question??
#include<stdio.h>
int main(void)
{ int a,b;
a=7;
b=9;
int c;
c=a/b;
switch(c)
{
case 0:
printf("Bigger is %d",b);
break;
default:
printf("Bigger is %d",a);
break;
}
return 0;
}
My Solution:
min=(a+b)/2 – abs(a-b)/2
max=(a+b)/2 + abs(a-b)/2
int main()
{
int a=7,b=9;
printf(“%d”,a>b?a:b);
}
Thank you so much madhu!!!!!
int find_max(int n1, int n2)
{
int r = n1-n2;
r = (r>>31)&1;
if(r=0)
return n1;
else
return n2;
}
correction: if(r==0)