Given two positive and distinct numbers, the task is to find the greatest of two given numbers without using any conditional statements(if...) and operators(?: in C/C++/Java).
Examples:
Input: a = 14, b = 15
Output: 15
Input: a = 14, b = 14
Output: 14
Input: a = 1233133, b = 124
Output: 1233133
The Approach is to return the value on the basis of the below expression:
c = a - b
flag = (c >> 31) & 1
(a * (1 - flag)) + (b * flag)Mathematical Explanation:
Let's break down the mathematical operations step by step:
- Difference Calculation:
- c=a−b
- Sign Check:
- Right shift the sign bit of c to the least significant bit:
- flag=(c>>31)&1
- This operation checks the sign of the integer:
- If c is positive or zero, flag will be 0.
- If c is negative, flag will be 1.
- Result Selection:
- Use the flag to determine the result:
- result=(a ×! flag) + (b × flag)
- Simplifying this:
- If flag=0
- result=(a ×1 ) + (b × 0) = a
- If flag=0
- result=(a × 0) + (b × 1) = b
#include <stdio.h>
// Function to find the largest number
int max(int a, int b)
{
int c = a - b;
int flag = (c >> 31) & 1;
return (a * !flag) + (b * flag);
}
int main()
{
int a = 78;
int b = 68;
printf("The maximum of %d and %d is %d\n", a, b, max(a, b));
a = 1233133;
b = 124;
printf("The maximum of %d and %d is %d\n", a, b, max(a, b));
a = 14;
b = 14;
printf("The maximum of %d and %d is %d\n", a, b, max(a, b));
return 0;
}
public class MaxOfTwoNumbers {
public static int max(int a, int b) {
int c = a - b;
int flag = (c >> 31) & 1;
return (a * (1 - flag)) + (b * flag);
}
public static void main(String[] args) {
int a = 78;
int b = 68;
System.out.println("The maximum of " + a + " and " + b + " is " + max(a, b));
a = 68;
b = 78;
System.out.println("The maximum of " + a + " and " + b + " is " + max(a, b));
a = 78;
b = 78;
System.out.println("The maximum of " + a + " and " + b + " is " + max(a, b));
}
}
//coded by anuja_mishra
def max(a, b):
c = a - b
flag = (c >> 31) & 1
return (a * (1 - flag)) + (b * flag)
a = 78
b = 68
print(f"The maximum of {a} and {b} is {max(a, b)}")
a = 68
b = 78
print(f"The maximum of {a} and {b} is {max(a, b)}")
a = 78
b = 78
print(f"The maximum of {a} and {b} is {max(a, b)}")
#coded by anuja_mishra
function max(a, b) {
var c = a - b;
var flag = (c >> 31) & 1;
return (a * (1 - flag)) + (b * flag);
}
let a = 78;
let b = 68;
console.log(`The maximum of ${a} and ${b} is ${max(a, b)}`);
a = 68;
b = 78;
console.log(`The maximum of ${a} and ${b} is ${max(a, b)}`);
a = 78;
b = 78;
console.log(`The maximum of ${a} and ${b} is ${max(a, b)}`);
//coded by anuja_mishra
Output
The maximum of 78 and 68 is 78 The maximum of 1233133 and 124 is 1233133 The maximum of 14 and 14 is 14
Time complexity: O(1)
Auxiliary space: O(1)