Sub topic 12
Binary GCD: Stein's Algorithm
This chapter assumes you have read the earlier chapters on Euclid's algorithm and its running time. You should also be comfortable with Python's bitwise operators: & (AND), | (OR), >> (right shift) and << (left shift).
Euclid's algorithm needs a division or modulo operation at every step. On most modern CPUs that is fine. On small microcontrollers, and for very large integers, division is slow compared with shifts and subtraction. Josef Stein published a GCD method in 1967 that uses only those cheaper operations. It is called the binary GCD algorithm.
The Four Identities
Stein's algorithm rests on four facts about the GCD of non-negative integers:
gcd(a, 0) = a. This is the same base case as Euclid's algorithm.- If
aandbare both even, thengcd(a, b) = 2 · gcd(a/2, b/2), because 2 is a common divisor. - If
ais even andbis odd, thengcd(a, b) = gcd(a/2, b). A factor of 2 inacannot be shared with an oddb. - If
aandbare both odd anda ≤ b, thengcd(a, b) = gcd(a, b − a). This is Euclid's subtraction step, andb − ais always even.
Rule 4 is the reason this runs faster than plain subtraction. The difference of two odd numbers is even, so rule 3 strips at least one bit off the result right away. The values cannot creep downward one small subtraction at a time.
The Algorithm
import math
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: # both even: rule 2
a >>= 1
b >>= 1
shift += 1
while a & 1 == 0: # make a odd: rule 3
a >>= 1
while b != 0:
while b & 1 == 0: # make b odd: rule 3
b >>= 1
if a > b:
a, b = b, a
b -= a # rule 4; b is now even or zero
return a << shift
print(binary_gcd(48, 18)) # 6
# Check against the standard library
for x in range(-50, 51):
for y in range(-50, 51):
assert binary_gcd(x, y) == math.gcd(x, y)
print("all checks passed")The test (a | b) & 1 == 0 is true only when the lowest bit of both numbers is 0, which means both are even. Throughout the main loop, a stays odd. The factor 2^shift removed at the start is put back by the final a << shift.
Tracing gcd(48, 18)
| Step | a | b | shift | Action |
|---|---|---|---|---|
| Start | 48 | 18 | 0 | Both even |
| 1 | 24 | 9 | 1 | Halve both; b is now odd |
| 2 | 3 | 9 | 1 | Halve a three times until odd |
| 3 | 3 | 6 | 1 | b is odd, a ≤ b, b = 9 − 3 |
| 4 | 3 | 3 | 1 | Halve b to 3 |
| 5 | 3 | 0 | 1 | b = 3 − 3 |
| End | 3 | 0 | 1 | Return 3 << 1 = 6 |
Common Errors
- Forgetting the shift. If you return
ainstead ofa << shift, every result loses its shared factors of 2. On the trace above you would get 3 instead of 6. - Skipping the zero check. If
ais 0, the loopwhile a & 1 == 0never ends, because 0 shifted right is still 0. - Negative inputs. In Python,
-6 >> 1is-3, and a negativebis never 0 after subtraction in the way the loop expects. Take absolute values first.
Comparing the Three Methods
| Method | Operations used | Steps for n-bit inputs | Weakness |
|---|---|---|---|
| Subtraction (Euclid's original) | Subtraction, comparison | Up to about 2^n | Very slow when one input is much larger |
| Division (Euclid's algorithm) | Modulo | O(n), with Fibonacci pairs as the worst case | Each modulo is expensive on some hardware |
| Binary (Stein) | Shift, subtraction, comparison | O(n) | More steps than division; branches are harder to predict |
Each pass through Stein's main loop removes at least one bit from b, so the loop runs at most about 2n times for n-bit inputs. Each step costs O(n) bit operations on big integers. That gives O(n²) overall, the same order as schoolbook Euclid. The binary method wins when each of its steps is much cheaper than a division.
Exercise
Trace binary_gcd(40, 12). Give the value of shift after the first loop, the values of a and b at the start of the main loop, and the final result.
Show answer
Both numbers are even twice: (40, 12) becomes (20, 6), then (10, 3), so shift = 2. Halving a gives 5, so the main loop starts with a = 5, b = 3. Swap to a = 3, b = 5, then b = 2, which halves to 1. Swap to a = 1, b = 3, then b = 2, which halves to 1. Then b = 1 − 1 = 0. The result is 1 << 2 = 4.
Exercise
Why does the main loop always make progress, even though it uses subtraction instead of division?
Show answer
At the subtraction both a and b are odd, so b − a is even, or zero. On the next pass the inner loop halves it at least once. The new b is therefore at most (b − a) / 2, which is less than half the old b. So b's bit length drops every pass, and the loop ends within about n passes for each n-bit value.