Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, July 22, 2016

Comparing two integers without any comparison

Comparing two integers without any comparison


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 will be zero.  {      cout << " b is greater than a";  }  else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.  {      cout << "a and b are equal";  }  else      cout << "a is greater than b";  

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

Answer by fmsf for Comparing two integers without any comparison


(!(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?

Answer by siukurnin for Comparing two integers without any comparison


I just cant see any good reason to do that : who would want to program without "if" ?

a possible answer is :

( ( a + b ) + abs ( a -b ) ) / 2

I guess "abs" just hides a "if" somewhere, just as the ternary operator that is just another name for "if" ...

Answer by Adam Hawes for Comparing two integers without any comparison


Not one of the samples presented in the question or any of the answers thus far protects from division by zero. Why on earth are you trying to avoid an 'if' statement? I suspect homework question about ?: operators.

cout << "Maximum is: " << ((a>b)?a:b)  

There we go.

It's not possible to compare two numbers without a comparison. You can fudge it and do an indirect operation, but at the end of the day you're comparing something. Trust the compiler to optimize the code and select the best operations.

Answer by Martin Beckett for Comparing two integers without any comparison


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.

Answer by Konrad Rudolph for Comparing two integers without any comparison


You might exploit the fact that the sign of the calculation a - b depends on which number is greater. This is used in many implementations of comparison. But I believe you'll never be able to completely avoid comparison. In this case, you still at least need to evaluate the contents of the sign flag on the processor.

If you just need to display the lower number you can also use arithmetic tricks:

result = ((a + b) - sqrt((a - b) * (a - b))) / 2  

EDIT erm ? you're allowed to use switch?

I should use switch statements and arithmetic operators.

switch is basically the same as chained if and as such it also uses comparison. This sounds as if you should indeed just compare to zero to see what sign a - b has.

Answer by Ameer Jewdaki for Comparing two integers without any comparison


mgb, thank you very much for your suggestion:

void greater(int a, int b) {      int c = a - b;      switch(c) {          case 0:              cout << "a and b are equal" << endl;              break;          default:              int d = c & (1<<31);              switch(d) {                  case 0:                      cout << "a is bigger than b" << endl;                      break;                  default:                      cout << "a is less than b" << endl;              }      }  }  

Thank you all for your helps and suggestions.

Answer by phy1729 for Comparing two integers without any comparison


char c c=0x3D + (!(b/a) && (a-b)) - (!(a/b) && (a-b)) printf("a %c b",c);

Answer by Vilx- for Comparing two integers without any comparison


The Perverse Idea: use an array of function pointers. Then with some arithmetic and bitwise operations get an index into that array.

Answer by Eclipse for Comparing two integers without any comparison


Here's a fun bit-twiddling version that doesn't have any conditional branches.

int g = (int)"greater";  int l = (int)"less";  int e = (int)"equal";    int a = 7;  int b = 10;    char *result = (char*)((((a - b) >> 31) & l) | (((b - a) >> 31) & g) | ((~((a - b) | (b - a))) >> 31) & e);  cout << result;  

Answer by Daniel Earwicker for Comparing two integers without any comparison


As a pointless exercise, here's a way of implementing a cond function - to serve the purpose of if, supposing it (and switch, and ?:) had somehow disappeared from the language, and you're using C++0x.

void cond(bool expr, std::function ifTrue, std::function ifFalse)  {      std::function choices[2] = { ifTrue, ifFalse };      choices[expr == false]();  }  

e.g.

cond(x > y,      /*then*/ [] { std::cout << "x is greater than y"; },      /*else*/ [] { std::cout << "x is not greater than y"; });  

Like I say, pointless.

Answer by user2879961 for Comparing two integers without any comparison


Try this, tested it, works well.

public static int compare(int a, int b)  {      int c = a - b;      return (c >> 31) & 1 ^ 1;  }  

Answer by kumar arvind gupta for Comparing two integers without any comparison


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    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;  }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.