Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically return the max of two integers without using any comparison operators and without using if, else, etc?

How do I programmatically return the maximum of two integers without using any comparison operators and without using if, else, etc?

like image 510
MrDatabase Avatar asked Oct 22 '08 20:10

MrDatabase


People also ask

How do you find the maximum of two numbers without comparison?

The basic logic is simple, let's say we have two numbers a & b if a-b>0(i.e. the difference is positive) then a is maximum else if a-b==0 then both are equal and if a-b<0(i.e. diff is -ve) b is maximum.

How do you check if two numbers are the same in Python?

If equals test in Python: if with == The equals ( == ) operator tests for equality. It returns True when both tested values are the same. When their values differ, the operator returns False .

How do you know if two integers are equal?

To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).


1 Answers

max: // Will put MAX(a,b) into a

a -= b;
a &= (~a) >> 31;
a += b;

And:

int a, b;

min: // Will put MIN(a,b) into a

a -= b;
a &= a >> 31;
a += b;

from here.

like image 96
plinth Avatar answered Oct 26 '22 14:10

plinth