Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get minimum or maximum of two number without using conditional statement. Max(a,b) MIN(a,b) implementation in CSharp/C#
int max(int a, int b)
{
/* max(a,b) = 1/2(a + b + |a-b|) */
Func<int, int> modValue = x => (int)Math.Sqrt(Math.Pow(x, 2));
return (int)Math.Ceiling((double)(a + b)/2 + ((double)modValue(a - b))/2);
}
int min(int a, int b)
{
/* max(a,b) = 1/2(a + b - |a-b|) */
Func<int, int> modValue = x => (int)Math.Sqrt(Math.Pow(x, 2));
return (int)Math.Ceiling(((double)(a + b) / 2 - ((double)modValue(a - b)) / 2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.