Below is my pseudo code.
function highest(i, j, k)
{
if(i > j && i > k)
{
return i;
}
else
Pseudocode:
result = i
if j > result:
result = j
if k > result:
result = k
return result
int greater = a>b ? (a>c? a:c) :(b>c ? b:c);
System.out.println(greater);
I like to eliminate conditional jumps as an intellectual exercise. Whether this has any measurable effect on performance I have no idea though :)
#include <iostream>
#include <limits>
inline int max(int a, int b)
{
int difference = a - b;
int b_greater = difference >> std::numeric_limits<int>::digits;
return a - (difference & b_greater);
}
int max(int a, int b, int c)
{
return max(max(a, b), c);
}
int main()
{
std::cout << max(1, 2, 3) << std::endl;
std::cout << max(1, 3, 2) << std::endl;
std::cout << max(2, 1, 3) << std::endl;
std::cout << max(2, 3, 1) << std::endl;
std::cout << max(3, 1, 2) << std::endl;
std::cout << max(3, 2, 1) << std::endl;
}
This bit twiddling is just for fun, the cmov
solution is probably a lot faster.
The easiest way to find a maximum or minimum of 2 or more numbers in c++ is:-
int a = 3, b = 4, c = 5;
int maximum = max({a, b, c});
int a = 3, b = 4, c = 5;
int minimum = min({a, b, c});
You can give as many variables as you want.
Interestingly enough it is also incredibly efficient, at least as efficient as Ignacio Vazquez-Abrams'solution (https://godbolt.org/z/j1KM97):
mov eax, dword ptr [rsp + 8]
mov ecx, dword ptr [rsp + 4]
cmp eax, ecx
cmovl eax, ecx
mov ecx, dword ptr [rsp]
cmp eax, ecx
cmovl eax, ecx
Similar with GCC, while MSVC makes a mess with a loop.
Not sure if this is the most efficient or not, but it might be, and it's definitely shorter:
int maximum = max( max(i, j), k);
#include<stdio.h>
int main()
{
int a,b,c,d,e;
scanf("%d %d %d",&a,&b,&c);
d=(a+b+abs(a-b))/2;
e=(d+c+abs(c-d))/2;
printf("%d is Max\n",e);
return 0;
}