Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created January 18, 2012 20:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cslarsen/1635213 to your computer and use it in GitHub Desktop.
Save cslarsen/1635213 to your computer and use it in GitHub Desktop.
Binary gcd algorithm in C++ using iteration and bit shifts
/*
* The binary gcd algorithm using iteration.
* Should be fairly fast.
*
* Put in the public domain by the author:
*
* Christian Stigen Larsen
* http://csl.sublevel3.org
*/
int binary_gcd(int u, int v)
{
int shl = 0;
while ( u && v && u!=v ) {
bool eu = !(u & 1);
bool ev = !(v & 1);
if ( eu && ev ) {
++shl;
u >>= 1;
v >>= 1;
}
else if ( eu && !ev ) u >>= 1;
else if ( !eu && ev ) v >>= 1;
else if ( u>=v ) u = (u-v)>>1;
else {
int tmp = u;
u = (v-u)>>1;
v = tmp;
}
}
return !u? v<<shl : u<<shl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment