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
gcd(A,B) is transformed according to the following rules:
If B=0, then gcd(A,B)=A
If A=0, then gcd(A,B)=B
If both A and B are even, then gcd(A,B)=2×gcd(2A,2B) because 2 is a common factor
If only A is even, then gcd(A,B)=gcd(2A,B), because B does not have a factor of 2
If only B is even, then gcd(A,B)=gcd(A,2B), because A does not have a factor of 2
If both A and B are odd, then gcd(A,B)=gcd(2∣A−B∣,min(A,B)) because gcd(A,B)=gcd(B,A), and if A>B, then gcd(A,B)=gcd(A−B,B). Since A−B is even, we divide it by 2.
Code
Written by Ryan Kim of Fractalyze
Last updated