# Thread: Find if number x is less than y without comparison operator.

1. ## Find if number x is less than y without less than operator.

This implementation is correct but inefficient.

Code:
```static int lessThan(int number1, int number2) {
int i = 1;
while (number1 && number2) {
number1 = number1 - 1;
number2 = number2 - 1;
}
if (number1 == 0) {
i = 0;
}
return i;
}``` 2. So what's == if it's not a comparison operator? 3. My mistake, I meant greater-less than operator. 4. As conjectured in your other topic: Originally Posted by Salem
Seems like one of those pointless exercises like add two numbers without using +

It seems the OP is lumbered with a tutor who thinks magic tricks is how you teach programming.
Is this true? 5. Well... no '<' operator here (hehe)...
Code:
```// Intel/AMD:
int lessThan(int a, int b)
{
int r = 0;

__asm__ __volatile__ (
"cmpl %2,%1\n\t"
"sets %b0"
: "+r" (r) : "r" (a), "g" (b) );

return r;
}```
Another way to do it, purely in C, but also potentially inneficient (in comparison of using '<'):
Code:
```#include <limits.h>

int lessThan( int a, int b )
{
unsigned int r = a - b;
return ( r >> (sizeof(int) * CHAR_BIT - 1) );
}```
And I agree with Salem... These kinds of exercises are pointless. 6. I would suggest that you evaluate this question the same way a CPU evaluates this question: do a subtraction, and then look at the resulting number.

A naive approach would be something like:

Code:
```     is_lt(a, b) // is a less than b?

diff = b - a

if diff is zero, a == b, so return false
if diff is negative, a < b, so return false
if diff is positive, b > a, so return true```
Tests:
• is_lt(4, 0) ? diff = 0 - 4 == -4 -> negative, return false
• is_lt(4, 4) ? diff = 4 - 4 == 0 -> zero, return false
• is_lt(4, 5) ? diff = 5 - 4 == 1 -> positive, return true

More tests:
• is_lt(-100, -101) diff = -101 - -100 == -1 -> negative, return false (whoops!)
• is_lt(100, -101) diff = -101 - 100 == -201 -> negative, return false (ok)
• is_lt(-101, 100) diff = 100 - -101 == 201 -> positive ,return true

So maybe if both are negative you have to switch things around?

How can you test for zero? Seems easy.
How can you test for negative/positive? It turns out this is super easy! Just look up how negative numbers are implemented in 2's-complement arithmetic and you're good to go! 7. Ahhh... and this works very well:
Code:
```int lessThan( int a, int b )
{ return (a - b) >> ( sizeof(int) * CHAR_BIT - 1 ); }```
Right shift with signed integers are "dependent of implementation", accondingly to ISO 9899, due to the fact that most processors implement "logical shifts" and "arithmetic shifts". If a logical shift is used the result will be 1 if a<b or 0, otherwise... if an arithmetic shift is used the result will be -1 if a < b, or 0, otherwise...

Of couse, assuming two's complement are used and msb is the sign bit. Popular pages Recent additions int, lessthanint, number1, number2, return 