Sub topic 12
Binary GCD: Stein's Algorithm
Every version of Euclid's algorithm so far has relied on division or subtraction. In 1967 Josef Stein published a method that uses only three cheap operations: testing whether a number is even, shifting bits right (halving), and subtraction. This chapter explains why it works, traces it by hand, proves that it finishes in a bounded number of steps, and compares it with the division-based and subtraction-based methods.
This chapter assumes you know the invariant gcd(a, b) = gcd(b, a mod b), Euclid's subtraction method, the handling of zero and negative inputs, and the logarithmic step bound from Lamé's theorem. You should also know Python's bitwise operators: & (AND), | (OR), >> (right shift), and << (left shift).
Why Avoid Division?
On many processors, integer division is much slower than addition, subtraction, or shifting. A 64-bit hardware divide can take tens of clock cycles, while a shift or a subtraction usually takes one. Small embedded chips may have no divide instruction at all, so division runs as a software routine. Arbitrary-precision libraries face the same issue on a larger scale, because dividing two multi-word numbers costs far more than shifting them.
Euclid's subtraction method already avoids division, but it can be very slow. gcd(1000000, 1) takes a million subtractions. Stein's algorithm keeps the cheap operations of the subtraction method and guarantees that the numbers shrink quickly.
The Four Identities
Stein's algorithm rests on four facts about gcd. Each holds for non-negative integers a and b.
| Case | Identity | Reason | Column | Column |
|---|---|---|---|---|
| One input is zero | gcd(a, 0) = a | Every integer divides 0 | ||
| Both even | gcd(2a, 2b) = 2 · gcd(a, b) | 2 is a common factor and can be pulled out | ||
| One even, one odd | gcd(2a, b) = gcd(a, b) when b is odd | 2 cannot divide an odd b, so the factor 2 of the even input does not contribute | ||
| Both odd | gcd(a, b) = gcd(\ | a − b\ | , min(a, b)) | This is Euclid's subtraction step |
The fourth identity has a property that makes the algorithm fast: the difference of two odd numbers is always even. Each subtraction therefore produces an even number, and the third identity lets you halve that number right away. Halving discards a whole bit, which is what drives the logarithmic running time.
Proof of the one-even, one-odd identity
Let b be odd. Any common divisor d of 2a and b divides b, so d is odd. An odd d that divides 2a must divide a, because d and 2 share no prime factors. So every common divisor of 2a and b is a common divisor of a and b. In the other direction, a common divisor of a and b also divides 2a. The two pairs have the same set of common divisors, so they have the same greatest one.
The Algorithm
The algorithm runs in three phases:
- Remove the common factors of two from both inputs and count them in
shift. - Remove the remaining factors of two from
a, which leavesaodd. That factor of two is not common to both inputs, so the third identity lets you drop it. - Repeat until
bis zero: makebodd, swap so thata ≤ b, then replacebwithb − a. The odd valueastays at least 1, and the result isashifted left byshift.
Here is the implementation:
def binary_gcd(a, b):
a, b = abs(a), abs(b)
if a == 0:
return b
if b == 0:
return a
shift = 0
while (a | b) & 1 == 0:
a >>= 1
b >>= 1
shift += 1
while a & 1 == 0:
a >>= 1
while b != 0:
while b & 1 == 0:
b >>= 1
if a > b:
a, b = b, a
b -= a
return a << shift
print(binary_gcd(48, 18)) # 6The test (a | b) & 1 == 0 checks that both numbers are even in one step. The lowest bit of a | b is 0 only when the lowest bit of each input is 0.
Tracing It by Hand
gcd(48, 18)
Both inputs are even, so halve once: (24, 9), shift = 1. Now 9 is odd and the first loop stops. Next, make a odd: 24 → 12 → 6 → 3.
| Step | a | b before | b made odd | swap? | b − a |
|---|---|---|---|---|---|
| 1 | 3 | 9 | 9 | no | 6 |
| 2 | 3 | 6 | 3 | no | 0 |
The loop ends with a = 3, and the function returns 3 << 1 = 6.
gcd(1071, 462)
1071 is odd, so shift = 0 and a = 1071 is already odd.
| Step | a | b before | b made odd | after swap (a, b) | new b = b − a |
|---|---|---|---|---|---|
| 1 | 1071 | 462 | 231 | (231, 1071) | 840 |
| 2 | 231 | 840 | 105 | (105, 231) | 126 |
| 3 | 105 | 126 | 63 | (63, 105) | 42 |
| 4 | 63 | 42 | 21 | (21, 63) | 42 |
| 5 | 21 | 42 | 21 | (21, 21) | 0 |
The result is 21, which matches the division-based trace from earlier chapters. Halving 462 to 231 in step 1 is safe because 1071 is odd. The factor 2 belonged only to 462.
Termination and the Step Bound
The proof has two parts.
Every loop terminates. The halving loops run only on positive even numbers, and halving reduces them, so each loop stops after at most log₂ of its input steps. In the main loop both a and b are odd and positive just before the subtraction, and a ≤ b. So b − a is even and non-negative, and a is unchanged.
The main loop runs at most about log₂ a + log₂ b times. Consider the product a · b at the start of each iteration. The subtraction replaces the larger value b with b − a, which is even. If it is zero the loop ends. Otherwise the next iteration halves it at least once, giving at most (b − a)/2 < b/2. So each iteration more than halves the product a · b, and the product stays at least 1 while both values are positive. For n-bit inputs, the product is below 2^(2n), so the main loop runs at most about 2n times.
Correctness. Each operation applies one of the four identities. Halving both inputs is the second identity, recorded in shift. Halving one value while the other is odd is the third. Subtracting two odd values is the fourth. So the gcd of the current pair, times 2^shift, never changes. When b reaches 0, the first identity gives gcd(a, 0) = a.
Speeding Up the Halving Loops
The bit-by-bit while x & 1 == 0 loops can be replaced by a single shift once you know how many trailing zero bits a number has. The expression x & -x isolates the lowest set bit of a positive integer, so (x & -x).bit_length() - 1 gives the number of trailing zeros. Hardware offers the same thing as a single instruction, for example ctz or tzcnt.
import math
import random
def trailing_zeros(x):
# Number of trailing zero bits in x, for x > 0
return (x & -x).bit_length() - 1
def binary_gcd_ctz(a, b):
a, b = abs(a), abs(b)
if a == 0:
return b
if b == 0:
return a
shift = trailing_zeros(a | b)
a >>= trailing_zeros(a)
while b != 0:
b >>= trailing_zeros(b)
if a > b:
a, b = b, a
b -= a
return a << shift
for _ in range(10000):
x = random.randint(-10**12, 10**12)
y = random.randint(-10**12, 10**12)
assert binary_gcd_ctz(x, y) == math.gcd(x, y)
print(binary_gcd_ctz(48, 18)) # 6The value trailing_zeros(a | b) equals the smaller trailing-zero count of a and b, which is the number of common factors of two. The randomized check compares the function with math.gcd, including negative values and zero.
Gotchas and Failure Modes
Zero causes an infinite loop
Zero is even, and halving it gives zero again. Without the early if a == 0 and if b == 0 returns, the loop while (a | b) & 1 == 0 never stops on gcd(0, 0), and while a & 1 == 0 never stops when a is 0. Handle the zero cases before any halving loop.
Negative inputs break the comparisons
In Python, -6 >> 1 is -3 and -3 & 1 is 1, so parity tests still work on negative numbers. The swap-and-subtract step does not. With a negative a, the comparison a > b and the subtraction no longer shrink the values toward zero, and the loop can run forever. Take absolute values first, as both implementations above do. In C and C++, use unsigned types. Right-shifting a negative signed value was implementation-defined in C++ before C++20 and still is in C, and abs(INT_MIN) overflows.
The final shift cannot overflow
The final shift a << shift cannot overflow a fixed-width type. The result is the gcd, which is at most the smaller nonzero input, so it already fits in the type that held the inputs.
Python does not benefit much
In pure Python each bitwise operation is an interpreted bytecode step, so the extra iterations of Stein's algorithm usually make it slower than the % loop. math.gcd is implemented in C and beats both. Stein's algorithm is worth using in C, Rust, assembly, hardware designs, and big-number libraries, not in everyday Python code.
Comparing the Three Methods
| Property | Division-based (Euclid) | Subtraction-based | Binary (Stein) |
|---|---|---|---|
| Operations per step | One division or modulo | One subtraction | Shifts, one comparison, one subtraction |
| Worst-case step count | About 1.44 · log₂(min) | Proportional to max/min, so linear in the value | About 2 · bits |
| Worst-case inputs | Consecutive Fibonacci numbers | (N, 1) for large N | Inputs with many bits that do not cancel quickly |
| Needs a divide instruction | Yes | No | No |
| Extends easily to Bézout coefficients | Yes, directly | Awkward | Possible, but more complex |
| Best fit | General-purpose code, interpreted languages | Teaching only | Hardware without fast division, constant-time or big-number libraries |
Use these criteria to choose:
- Use the standard library (
math.gcd,std::gcd) unless you have measured a reason not to. Several standard libraries already use a binary GCD internally. - Choose the division-based algorithm when you also need Bézout coefficients or modular inverses, or when division is fast on the target.
- Choose Stein's algorithm when division is slow or missing, or when you work with multi-word numbers where shifts are cheap and division is expensive.
- Avoid the pure subtraction method in real code. Its step count can grow linearly with the size of the input values.
Exercise
Trace binary_gcd(84, 120) by hand. Give the value of shift, the odd value of a after the second phase, each (a, b) pair in the main loop, and the final result.
Show answer
Both inputs are even: (84, 120) → (42, 60) → (21, 30), so shift = 2 and a = 21 is already odd. Main loop: b = 30 is made odd → 15; since 21 > 15, swap to (15, 21); b = 21 − 15 = 6. Next, b = 6 → 3; swap to (3, 15); b = 12. Next, b = 12 → 3; no swap (3, 3); b = 0. The result is 3 << 2 = 12, and gcd(84, 120) = 12.
Exercise
Why is it safe to halve b in the main loop without changing shift, while halving in the first phase must increment shift?
Show answer
In the main loop a is always odd, so a factor of 2 in b is not a common factor and the identity gcd(2x, y) = gcd(x, y) for odd y applies. In the first phase both values are even, so 2 divides both and belongs to the gcd. The identity gcd(2x, 2y) = 2 · gcd(x, y) requires recording that factor, which shift does.
Exercise
Remove the two zero checks from binary_gcd and call it with (0, 5). What happens, and why?
Show answer
The first loop is skipped, because 0 | 5 = 5 is odd. The loop "while a & 1 == 0" then runs forever: a is 0, 0 & 1 is 0, and 0 >> 1 is still 0. Zero is even but never shrinks under halving, so the zero cases must be handled before any halving loop.