Reference articles on history, science, culture and more
Encyclopedia

Binary GCD algorithm

Algorithm for computing the greatest common divisor

Image credit is listed at the end of this article.

The binary GCD algorithm, also known as Stein's algorithm or the binary Euclidean algorithm, is an algorithm that computes the greatest common divisor (GCD) of two nonnegative integers. Stein's algorithm uses simpler arithmetic operations than the conventional Euclidean algorithm; it replaces division with arithmetic shifts, comparisons, and subtraction.

Although the algorithm in its contemporary form was first published by the physicist and programmer Josef Stein in 1967, it was known by the 2nd century BCE, in ancient China.

01Algorithm

The algorithm finds the GCD of two nonnegative numbers u and v by repeatedly applying these identities:

  1. \gcd(u,0)=u: everything divides zero, and u is the largest number that divides u.
  2. \gcd(2u,2v)=2\cdot \gcd(u,v): 2 is a common divisor.
  3. \gcd(u,2v)=\gcd(u,v) if u is odd: 2 is then not a common divisor.
  4. \gcd(u,v)=\gcd(u,v-u) if u,v odd and u\leq v.

As GCD is commutative (\gcd(u,v)=\gcd(v,u)), those identities still apply if the operands are swapped: \gcd(0,v)=v, \gcd(2u,v)=\gcd(u,v) if v is odd, etc.

02Implementation

While the above description of the algorithm is mathematically correct, the binary GCD algorithm performs more loop iterations that the Euclidean one, so it only offers a performance advantage if those iterations are substantially faster. Performant software implementations typically differ from it in a few notable ways:

  • eschewing repeated trial division by 2 in favour of the count trailing zeros primitive and a single bit shift, which is functionally equivalent to repeatedly applying identity 3, but much faster;
  • expressing the algorithm iteratively rather than recursively: the resulting implementation can be laid out to avoid repeated work, invoking identity 2 at the start and maintaining as invariant that both numbers are odd upon entering the loop, which only needs to implement identities 3 and 4; and
  • making the loop's body branch-free except for its exit condition v == 0: unpredictable branches can have a large, negative impact on performance.

The following is an implementation of the algorithm in C.

// Count trailing zeros. This is a pedagogical example only; // for efficiency use __builtin_ctzll() or similar. static int ctz(uint64_t n) { int s = 0, t; while ((t = n & 15) == 0) { n >>= 4; s += 4; } return s + ((0x12131210 >> 2*t) & 3); } uint64_t gcd(uint64_t u, uint64_t v) { if (!u || !v) return u | v; // Identity #1 int shift = ctz(u | v); u >>= ctz(u); uint64_t min, max; while (v) { v >>= ctz(v); // Identity #3 min = (u < v) ? u : v; // Identity #4 max = (u > v) ? u : v; u = min; v = max - min; } return u << shift; // Identity #2 }


The following is an implementation of the algorithm in Rust exemplifying those differences, adapted from uutils. The conditional exchange of u and v (ensuring u\leq v) compiles down to conditional moves;:

pub fn gcd(mut u: u64, mut v: u64) -> u64 { // Base cases: gcd(n, 0) = gcd(0, n) = n if u == 0 { return v; } else if v == 0 { return u; } // Using identities 2 and 3: // gcd(2ⁱ u, 2ʲ v) = 2ᵏ gcd(u, v) with u, v odd and k = min(i, j) // 2ᵏ is the greatest power of two that divides both 2ⁱ u and 2ʲ v let i = u.trailing_zeros(); u >>= i; let j = v.trailing_zeros(); v >>= j; let k = i.min(j); loop { // u and v are odd at the start of the loop debug_assert!(u % 2 == 1, "u = {} should be odd", u); debug_assert!(v % 2 == 1, "v = {} should be odd", v); // Swap if necessary so u ≤ v if u > v { (u, v) = (v, u); } // Identity 4: gcd(u, v) = gcd(u, v-u) as u ≤ v and u, v are both odd v -= u; // v is now even if v == 0 { // Identity 1: gcd(u, 0) = u // The shift by k is necessary to add back the 2ᵏ factor that was removed before the loop return u << k; } // Identity 3: gcd(u, 2ʲ v) = gcd(u, v) as u is odd v >>= v.trailing_zeros(); } }

Note: The implementation above accepts unsigned (non-negative) integers; given that \gcd(u,v)=\gcd(\pm {}u,\pm {}v), the signed case can be handled as follows:

/// Computes the GCD of two signed 64-bit integers /// The result is unsigned and not always representable as i64: gcd(i64::MIN, i64::MIN) == 1 << 63 pub fn signed_gcd(u: i64, v: i64) -> u64 { gcd(u.unsigned_abs(), v.unsigned_abs()) }

03Complexity

Asymptotically, the algorithm requires O(n) steps, where n is the number of bits in the larger of the two numbers, as every two steps reduce at least one of the operands by at least a factor of 2. Each step involves only a few arithmetic operations (O(1) with a small constant); when working with word-sized numbers, each arithmetic operation translates to a single machine operation, so the number of machine operations is on the order of n, i.e. \log _{2}(\max(u,v)).

For arbitrarily large numbers, the asymptotic complexity of this algorithm is O(n^{2}), as each arithmetic operation (subtract and shift) involves a linear number of machine operations (one per word in the numbers' binary representation). If the numbers can be represented in the machine's memory, i.e. each number's size can be represented by a single machine word, this bound is reduced to: O\left({\frac {n^{2}}{\log _{2}n}}\right)

This is the same as for the Euclidean algorithm, though a more precise analysis by Akhavi and Vallée proved that binary GCD uses about 60% fewer bit operations.

04Extensions

The binary GCD algorithm can be extended in several ways, either to output additional information, deal with arbitrarily large integers more efficiently, or to compute GCDs in domains other than the integers.

The extended binary GCD algorithm, analogous to the extended Euclidean algorithm, fits in the first kind of extension, as it provides the Bézout coefficients in addition to the GCD: integers a and b such that a\cdot {}u+b\cdot {}v=\gcd(u,v).

In the case of large integers, the best asymptotic complexity is O(M(n)\log n), with M(n) the cost of n-bit multiplication; this is near-linear and vastly smaller than the binary GCD algorithm's O(n^{2}), though concrete implementations only outperform older algorithms for numbers larger than about 64 kilobits (i.e. greater than 8×1019265). This is achieved by extending the binary GCD algorithm using ideas from the Schönhage-Strassen algorithm for fast integer multiplication.

The binary GCD algorithm has also been extended to domains other than natural numbers, such as Gaussian integers, Eisenstein integers, quadratic rings, and integer rings of number fields.

05Historical description

An algorithm for computing the GCD of two numbers was known in ancient China, under the Han dynasty, as a method to reduce fractions:

If possible halve it; otherwise, take the denominator and the numerator, subtract the lesser from the greater, and do that alternately to make them the same. Reduce by the same number.

, Fangtian, Land surveying, The Nine Chapters on the Mathematical Art

The phrase "if possible halve it" is ambiguous,

  • if this applies when either of the numbers become even, the algorithm is the binary GCD algorithm;
  • if this only applies when both numbers are even, the algorithm is similar to the Euclidean algorithm.
Watch videos about Binary GCD algorithmExplainers and documentaries on YouTube (opens in a new tab)

Sources and credits

This article is adapted from the Wikipedia article Binary GCD algorithm, written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.

Images, from Wikimedia Commons:

Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.