Max of two numbers without conditional statements, ternary operator or relational operators
Last Updated :
04 Oct, 2023
Given two integers a and b, the task is to find the greatest of two given numbers without using any conditional statements (such as if and switch), the ternary operator ((condition X)? if X is true: if X is false;) or relational operators (such as <, >, <=, >=, ==, !=).
Examples:
Input: a = 86, b = 34
Output: 86
Input: a = -56, b = -78
Output: -56
Input: a = 789, b = 789
Output: 789
Approach: To solve the problem follow the below idea:
The approach is to use coordinate geometry to find the mid-point of the line drawn by adding the distance from the higher point to the lower point and also adding the distance from the lower point to the higher point. This can be done by using the mathematical expression given below:
f(x, y) = {(|x – y|) + (x + y)} ÷ 2
Implementation of this mathematical expression into a function that takes two integers and returns the greater integer:
C++
#include <iostream>
using namespace std;
int GreaterOfTwo( int x, int y)
{
return ( abs (x - y) + (x + y)) / 2;
}
int main()
{
int a, b;
a = 86, b = 34;
cout << GreaterOfTwo(a, b);
return 0;
}
|
Java
import java.lang.Math;
public class GreaterOfTwo {
public static int greaterOfTwo( int x, int y) {
return (Math.abs(x - y) + (x + y)) / 2 ;
}
public static void main(String[] args) {
int a, b;
a = 86 ;
b = 34 ;
System.out.println(greaterOfTwo(a, b));
}
}
|
Python3
def greater_of_two(x, y):
return ( abs (x - y) + (x + y)) / / 2
def main():
a, b = 86 , 34
print (greater_of_two(a, b))
if __name__ = = "__main__" :
main()
|
C#
using System;
namespace CodeTranslation
{
class Program
{
static int GreaterOfTwo( int x, int y)
{
return (Math.Abs(x - y) + (x + y)) / 2;
}
static void Main( string [] args)
{
int a, b;
a = 86;
b = 34;
Console.WriteLine(GreaterOfTwo(a, b));
}
}
}
|
Javascript
function greaterOfTwo(x, y) {
return Math.floor((Math.abs(x - y) + (x + y)) / 2);
}
let a = 86, b = 34;
console.log(greaterOfTwo(a, b));
|
Time complexity: O(1)
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...