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

For questions and feedback, please use the comments section below. Thanks for visiting.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *