Skip to content

Instantly share code, notes, and snippets.

@adamvduke
Created August 29, 2012 00:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamvduke/3505558 to your computer and use it in GitHub Desktop.
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
#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;
}
@Sam-Belliveau
Copy link

This is not parented, other people have discovered this code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment