| • Science | • People | • Locations | • Timeline |
The algorithm reduces the problem of finding the GCD by repeatedly applying these identities:
Following is a straightforward implementation of the algorithm in the C programming language, taking two positive arguments u and v and using only bit operations and subtraction. It first removes all common factors of 2 using identity 1, computes the gcd of the remaining numbers using identities 2 through 5, then combines these to form the final answer:
unsigned int gcd(unsigned int u, unsigned int v) { unsigned int k = 0; while ((u & 1) == 0 && (v & 1) == 0) { /* while both u and v are even */ u >>= 1; /* shift u right, dividing it by 2 */ v >>= 1; /* shift v right, dividing it by 2 */ k++; /* add a power of 2 to the final result */ } /* At this point either u or v (or both) is odd */ do { if ((u & 1) == 0) /* if u is even */ u >>= 1; /* divide u by 2 */ else if ((v & 1) == 0) /* else if v is even */ v >>= 1; /* divide v by 2 */ else if (u >= v) /* u and v are both odd */ u = (u-v) >> 1; else /* u and v both odd, v > u */ v = (v-u) >> 1; } while (u > 0); return v << k; /* returns v * 2^k */ }Efficiency can be enhanced on platforms with special instructions to find the least significant 1 bit in a word, allowing trailing zero bits to be removed in much larger groups. The latter while loop also benefits greatly from branch predication, which enables it to avoid many of the expensive branches caused by the many conditionals.
The algorithm requires O((log2 uv)2) worst-case time, or in other words time proportional to the square of the number of bits in u and v together. Although each step reduces at least one of the operands by at least 2 times, the subtract and shift operations do not take constant time for very large integers (although they're still quite fast in practice, requiring about one operation per word of the representation).
Although this algorithm can outperform the traditional Euclidean algorithm on many platforms, its asymptotic performance is the same, it is considerably more complex, and it does not generalize to negative integers or other fields such as polynomials where division with remainder is defined, nor does it have an extended version analogous to the extended Euclidean algorithm.