Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Created August 15, 2017 17:21
Show Gist options
  • Save vendettamit/33bf0d5839e07e624d372e2dc53d1580 to your computer and use it in GitHub Desktop.
Save vendettamit/33bf0d5839e07e624d372e2dc53d1580 to your computer and use it in GitHub Desktop.
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