Binary Euclidean Algorithm
Objective
The Binary Euclidean Algorithm, also known as Stein’s algorithm, is an efficient method for computing the greatest common divisor (GCD) of two integers. Unlike the standard Euclidean algorithm, which relies on division, the binary version replaces division with more efficient bitwise operations such as shifts and subtractions. This makes it highly suitable for implementation in both hardware and low-level software.
Core Idea
is transformed according to the following rules:
If , then
If , then
If both and are even, then because 2 is a common factor
If only is even, then , because does not have a factor of 2
If only is even, then , because does not have a factor of 2
If both and are odd, then because , and if , then . Since is even, we divide it by 2.
Code
def binary_gcd(a, b):
# Base case
if a == 0: return b
if b == 0: return a
# Case: both even
if a % 2 == 0 and b % 2 == 0:
return 2 * binary_gcd(a // 2, b // 2)
# Case: a even, b odd
elif a % 2 == 0:
return binary_gcd(a // 2, b)
# Case: a odd, b even
elif b % 2 == 0:
return binary_gcd(a, b // 2)
# Case: both odd
elif a >= b:
return binary_gcd((a - b) // 2, b)
else:
return binary_gcd((b - a) // 2, a)
Last updated