Maximum and minimum using mathematical formules.

Hey guys .. I need some help.. I need to find the maximum of two numbers using mathematical formules. I found two of them : ((a+b) + abs(a-b))/2; and int(a > b) * a + int(b > a) * b; .. Can you help me please with a third ? Thanks.
How mathematical do they have to be? I see you're allowed comparisons. Is this allowed?

a > b ? a : b
not thernary .. just math formula .. dont look at comparisons .. Mathematical formula without comparison :))
int(a > b) * a + int(b > a) * b

Won't work if a == b. Change one of those > to >=. (It's also a comparison ... which you have just excluded!)

Do you have any other restrictions on a and b? e.g. are they both integers and/or are they both positive?

If they are strictly positive integers then the following would work. If they aren't ... it won't. There are no comparisons.
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
   int a, b;
   cout << "Input a and b: ";   cin >> a >> b;
   cout << "Maximum is " << ( 1 && a / ( b + 1 ) ) * a + ( 1 && b / a ) * b ;
}



The following would work for any integers, but it looks ludicrous.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
   int a, b;
   cout << "Input a and b: ";   cin >> a >> b;
   int shift = abs( a ) + abs( b ) + 1;     // added to make comparators strictly positive
   cout << "Maximum is " << ( 1 && (a+shift) / (b+shift+1) ) * a + ( 1 && (b+shift)/(a+shift) ) * b ;
}
Last edited on
closed account (48T7M4Gy)
It's simple
Last edited on


max = (int)(a/b)*b + (int)(b/a)*a);

this won't work if equal. Not sure if that can be cured easily.
idea is that one or the other side is zero and the other side is the original value. The zero side is zero because the denominator is the larger value. If I did the order of operations right (?) ... I don't have much time today so this could have some issue.


Topic archived. No new replies allowed.