Skip to content

Instantly share code, notes, and snippets.

@sailfish009
Forked from cslarsen/binary_gcd.cpp
Created April 21, 2019 05:44
Show Gist options
  • Save sailfish009/67d1284542298571f01be4b248b71dee to your computer and use it in GitHub Desktop.
Save sailfish009/67d1284542298571f01be4b248b71dee 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