C++ gurus and learners, we program ourselves :P all work is CC licensed

Wednesday, November 6

Smallest Integer Without Using Comparison Operator


#include <iostream>
using namespace std;
#define CHAR_BIT 8

/*Function to find minimum of x and y*/
int min(int x, int y)
{
  return  y + ((x - y) & ((x - y) >>
            (sizeof(int) * CHAR_BIT - 1)));
}

/* Function to find minimum of 3 numbers x, y and z*/
int smallest(int x, int y, int z)
{
    return min(x, min(y, z));
}

int main()
{
   int x = 12, y = 15, z = 5;
   cout << "Minimum of 3 numbers is " << smallest(x, y, z) << endl;
   return 0;
}

9 comments :

  1. I have seen this code earlier and shall post a variation of this code soon :D

    ReplyDelete
  2. how did you think of this logic btw :P

    ReplyDelete
  3. This operator has multiple uses, we use it for cout, we use it for bit shifting in binary and we can overload it to perform other tasks that may seem better to be performed that way.

    ReplyDelete
  4. what is this << operator, we use it for cout?

    ReplyDelete
  5. @Hamza Iqbal says: the logical &(AND) and then using sum operator in line 8 ensures that minimum of the two is selected.

    ReplyDelete
  6. The architecture is usually 32 bit hence we assumed sizeof(int) will return 4 else it will be 8 on 64 bit architecture

    ReplyDelete
  7. Code Explanations:
    Line#__Explanation
    3______We define a constant 8 telling char has 8 bits
    8 & 9 __sizeof(int) will return 4 as 4 bytes are used by integers, so it becomes (4*8-1) = 31 which means x-y will be shifted 31 bits to left, this leaves us only with MSB of (x-y) which is then logical & with x-y itself again to set sign of integer, this signed integer when added with second number will return the value of minimum number of the two :)

    ReplyDelete
  8. This code was inspired from codeplaza.org team

    ReplyDelete