Maximum of four numbers without using conditional or bitwise operator
Given four numbers, print the maximum of the 4 entered numbers without using conditional or bitwise operator (not even ternary operators). Examples:
Input : 4 8 6 5
Output : 8
Input : 11 17 8 17
Output : 17
We use the fact that value of “(x – y + abs(x – y))” will be 0 of x is less than or equal to y. We use this value as index in an array of size 2 to pick maximum. Once we have found maximum of two elements, we can use same technique for finding maximum of all.
C++
#include <bits/stdc++.h>
using namespace std;
int maxOfFour( int w, int x, int y, int z)
{
int a[2];
a[0] = w, a[1] = x;
bool b = (a[0] - a[1] + abs (a[0] - a[1]));
swap(a[0], a[!b]);
a[1] = y;
b = (a[0] - a[1] + abs (a[0] - a[1]));
swap(a[0], a[!b]);
a[1] = z;
b = (a[0] - a[1] + abs (a[0] - a[1]));
swap(a[0], a[!b]);
return a[0];
}
int main()
{
int w = 12, x = 15, y = 18, z = 17;
cout << "Maximum of four : "
<< maxOfFour(w, x, y, z);
return 0;
}
|
Python
def maxOfFour(w, x, y, z):
a = [ 0 ] * 2
a[ 0 ] = w
a[ 1 ] = x
b = bool (a[ 0 ] - a[ 1 ] + abs (a[ 0 ] - a[ 1 ]))
if b:
b = 1
else :
b = 0
a[ 0 ], a[ 1 - b] = a[ 1 - b], a[ 0 ]
a[ 1 ] = y
b = bool (a[ 0 ] - a[ 1 ] + abs (a[ 0 ] - a[ 1 ]))
if b:
b = 1
else :
b = 0
a[ 0 ], a[ 1 - b] = a[ 1 - b], a[ 0 ]
a[ 1 ] = z
b = bool (a[ 0 ] - a[ 1 ] + abs (a[ 0 ] - a[ 1 ]))
if b:
b = 1
else :
b = 0
a[ 0 ], a[ 1 - b] = a[ 1 - b], a[ 0 ]
return a[ 0 ]
w = 12
x = 15
y = 18
z = 17
print ( "Maximum of four : " , maxOfFour(w, x, y, z))
|
C#
using System;
class Program
{
static int MaxOfFour( int w, int x, int y, int z)
{
int [] a = new int [2];
a[0] = w;
a[1] = x;
bool b = (a[0] - a[1] + Math.Abs(a[0] - a[1])) != 0;
Swap( ref a[0], ref a[Convert.ToInt32(!b)]);
a[1] = y;
b = (a[0] - a[1] + Math.Abs(a[0] - a[1])) != 0;
Swap( ref a[0], ref a[Convert.ToInt32(!b)]);
a[1] = z;
b = (a[0] - a[1] + Math.Abs(a[0] - a[1])) != 0;
Swap( ref a[0], ref a[Convert.ToInt32(!b)]);
return a[0];
}
static void Swap( ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main()
{
int w = 12, x = 15, y = 18, z = 17;
Console.WriteLine( "Maximum of four: " + MaxOfFour(w, x, y, z));
}
}
|
Output:
Maximum of four : 18
This article is contributed by
Arkajyoti Banerjee
. If you like GeeksforGeeks and would like to contribute, you can also write an article using
write.geeksforgeeks.org
or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Last Updated :
31 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...