BinaryGcd (Binary gcd v1.0.0)
A module implementing the binary GCD algorithm (also known as Stein's algorithm).
The binary GCD algorithm is an efficient method for computing the greatest common divisor of two non-negative integers. It uses only subtraction and bit operations, making it particularly fast for large numbers.
Algorithm Overview
The binary GCD algorithm works by:
- If both numbers are even, divide both by 2 and multiply the result by 2
- If one number is even, divide it by 2
- If both numbers are odd, subtract the smaller from the larger
- Repeat until one number becomes zero
Performance
This algorithm is generally faster than the Euclidean algorithm for large numbers because it avoids expensive division operations, using only bit shifts and subtraction.
Examples
iex> BinaryGcd.of(48, 18)
6
iex> BinaryGcd.of(0, 5)
5
iex> BinaryGcd.of(12, 0)
12
iex> BinaryGcd.of(54, 24)
6
Summary
Functions
@spec of(non_neg_integer(), non_neg_integer()) :: non_neg_integer()
Computes the greatest common divisor of two non-negative integers using the binary GCD algorithm.
Parameters
m
- First non-negative integern
- Second non-negative integer
Returns
- The greatest common divisor of
m
andn
Examples
iex> BinaryGcd.of(48, 18)
6
iex> BinaryGcd.of(0, 5)
5
iex> BinaryGcd.of(12, 0)
12
iex> BinaryGcd.of(54, 24)
6
iex> BinaryGcd.of(17, 13)
1
Algorithm Steps
- Base cases: If either number is 0, return the other number
- Both even: If both numbers are even, divide both by 2, compute GCD, then multiply by 2
- One even: If only one number is even, divide it by 2 and continue
- Both odd: If both numbers are odd, subtract the smaller from the larger and continue
- Recursion: Continue until one number becomes zero