Created
August 15, 2017 17:21
-
-
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#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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