Maximum of two numbers in c
Maximum of two numbers without comparison
Write a C++ function which takes two positive integers x and y as input then return x if x > y otherwise return y. Assume x is not equal to y. You are not allowed to use any comparison operator or any if statement.
Solution: maximum of two numbers using bitwise
Let max = a * x + b * y so we need to find a and b such that max = x when x > y and max = y when y > x. Note that a = 1 and b = 0 if x > y also a = 0 and b = 1 if y > x let d = x – y then take the most significant bit of d. If it is 1 then the difference is negative which means y > x. if it is 0 then the difference is positive which means x > y. Let the most significant bit k then we should have a = 1 – k and b = k
Code
Here is a c program for maximum of two numbers without if-else
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//Includes #include <iostream> using namespace std; //Function prototype int MAX (int, int); //Main function void main() { //Print Max cout << "Max = " << MAX(0, 1) << endl; } //Function receives two positive integers as input int MAX (int x, int y) { //Take the difference unsigned int d = x - y; //Get the most significant bit int k = d >> 31; //Choose a and b int a = 1 - k; int b = k; //Return max return a * x + b * y; } |
For questions and feedback, please use the comments section below. Thanks for visiting.