Is it possible to find the greatest of two integers without any comparison? I found some solutions:
if(!(a/b)) // if a is less than b then division result
char c;
c=0x3D + (!(b/a) && (a-b)) - (!(a/b) && (a-b));
printf("a %c b",c);
(!(a/b) ? cout << " b is greater than a" : (!(b-a) ? cout << "a and b are equal" : cout << "a is greater than b") : cout << "a is greater than b");
That gets a bit messy though
Edit: Is this homework?
Try this, tested it, works well.
public static int compare(int a, int b)
{
int c = a - b;
return (c >> 31) & 1 ^ 1;
}
To get the greatest number without using comparison/relational operator
void PrintGreatestNumber(int a, int b)
{
int [] x = new int[] { -1, 0, 1 };
int greatestNumber = ((a+b)+ x[ 1 + ((a-b) >> 31) - (-(a-b) >> 31)] * (a-b)) /2;
Console.WriteLine(greatestNumber);
}
Subtract them and check the sign using nasty bit twiddling hacks
http://graphics.stanford.edu/~seander/bithacks.html
Don't do this in production code if the other programmers know where you live.
I think this method is better than others, you can use this logic c and java both programming languages but int should be of 4 byte if int is of 2 byte then make 15 byte right shift instead of 31 byte.
enter code here
#include<stdio.h>
main()
{
int a, b;
printf("Enter three numbers\n");
scanf("%d %d", &a, &b);
printf("Largest number is %d \n",findMax( a,b ));
}
int findMax( int x, int y)
{
int z = x - y;
int i = (z >> 31) & 0x1;
printf("i = %d shift = %d \n", i, (z>>31));
int max = x - i * z;
return max;
}