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: 86Input: a = -56, b = -78
Output: -56Input: 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:
// Program to find the greater integer // among 2 integers #include <iostream> using namespace std;
// Function to find the greater integer int GreaterOfTwo( int x, int y)
{ // mid-point
return ( abs (x - y) + (x + y)) / 2;
} // Driver function int main()
{ int a, b;
a = 86, b = 34;
// Function Call
cout << GreaterOfTwo(a, b);
return 0;
} // This code is contributed by Shashank Kothari(Johnny). |
import java.lang.Math;
// Class to find the greater integer among 2 integers public class GreaterOfTwo {
// Function to find the greater integer
public static int greaterOfTwo( int x, int y) {
// Calculate the mid-point
return (Math.abs(x - y) + (x + y)) / 2 ;
}
// Main method (Driver function)
public static void main(String[] args) {
int a, b;
a = 86 ;
b = 34 ;
// Function Call and Print the result
System.out.println(greaterOfTwo(a, b));
}
} //Contributed by Aditi Tyagi |
# Function to find the greater integer among 2 integers def greater_of_two(x, y):
# mid-point
return ( abs (x - y) + (x + y)) / / 2
# Driver function def main():
a, b = 86 , 34
# Function Call
print (greater_of_two(a, b))
if __name__ = = "__main__" :
main()
|
using System;
namespace CodeTranslation
{ class Program
{
// Function to find the greater integer
static int GreaterOfTwo( int x, int y)
{
// mid-point
return (Math.Abs(x - y) + (x + y)) / 2;
}
static void Main( string [] args)
{
int a, b;
a = 86;
b = 34;
// Function Call
Console.WriteLine(GreaterOfTwo(a, b));
}
}
} |
// Function to find the greater integer function greaterOfTwo(x, y) {
// mid-point
return Math.floor((Math.abs(x - y) + (x + y)) / 2);
} // Driver function let a = 86, b = 34;
// Function Call
console.log(greaterOfTwo(a, b));
// This code is contributed by - Dwaipayan Bandyopadhyay |
86
Time complexity: O(1)
Auxiliary space: O(1)