To find max and min of two number

This program is to find max and min of a given two numbers.

Logic:
result = b ^ ((a ^ b) & -(a < b)); // min(a, b)

In above expression,if a < b, then -( a < b) become -1, so it behave like below expression

result = b ^ ((a ^ b) & ~0);

result = b ^ a ^ b; // b^b is zero

result = a ^ 0; // oring with 0 does not effect

result = a; //minimum number

result = a ^ ((a ^ b) & -(a < b)); // max(a, b) In above expression, if a > b, then -( a > b) become 0, so it behave like below expression
result = a ^ ((a ^ b) & -(0));
result = a ^ 0; // ORing with 0 does not effect
result = a; //Maximum number

Implementation

#include <stdio.h>
#define MAX(num1, num2) ( num1 ^ ((num1 ^ num2) & -(num1 < num2)))
#define MIN(num1, num2) ( num2 ^ ((num1 ^ num2) & -(num1 < num2)))

int main()
{
  int num1,num2;
  
  printf("\n Enter the number: ");
  scanf("%d", &num1);
  
  printf("\n Enter the number: ");
  scanf("%d", &num2);
  
  printf("\n The maximum is: %d\n", MAX(num1, num2));
  printf("\n The minimum is: %d\n", MIN(num1, num2));
  

  return 0;
}

Output:

Enter the number: 10

Enter the number: 18

The maximum is: 18

The minimum is: 10


Categories: Data Structure and Algorithm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: