Created
August 29, 2012 00:17
-
-
Save adamvduke/3505558 to your computer and use it in GitHub Desktop.
A C function to compute an average without the risk of integer overflow
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
#include <stdio.h> | |
/* https://twitter.com/mikeash/status/240471662422810624 | |
* Compute average with no possibility of integer overflow. | |
* Note: patented in 1996, so you can't use it! | |
*/ | |
int patentedAverage(int a, int b) | |
{ | |
int av = (a/2) + (b/2) + (a&b&1); | |
return av; | |
} | |
/* http://aggregate.org/MAGIC/#Average%20of%20Integers */ | |
int alternativeAverage(int a, int b) | |
{ | |
int av = (a&b)+((a^b)>>1); | |
return av; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int a = 10; | |
int b = 20; | |
int av = patentedAverage(a, b); | |
printf("Patented average: %d\n", av); | |
int alt = alternativeAverage(a, b); | |
printf("Alternative average: %d\n", alt); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not parented, other people have discovered this code