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:

  1. If both numbers are even, divide both by 2 and multiply the result by 2
  2. If one number is even, divide it by 2
  3. If both numbers are odd, subtract the smaller from the larger
  4. 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

Computes the greatest common divisor of two non-negative integers using the binary GCD algorithm.

Functions

of(m, n)

Computes the greatest common divisor of two non-negative integers using the binary GCD algorithm.

Parameters

  • m - First non-negative integer
  • n - Second non-negative integer

Returns

  • The greatest common divisor of m and n

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

  1. Base cases: If either number is 0, return the other number
  2. Both even: If both numbers are even, divide both by 2, compute GCD, then multiply by 2
  3. One even: If only one number is even, divide it by 2 and continue
  4. Both odd: If both numbers are odd, subtract the smaller from the larger and continue
  5. Recursion: Continue until one number becomes zero