M34 · Math

Euclid’s Algorithm: GCD and LCM

Euclid’s algorithm replaces a pair of numbers by a smaller pair with the same common divisors until one of them is zero. This lesson proves the key step, bounds the number of steps with Fibonacci numbers, derives the lcm safely, and lists the built-ins and overflow rules of C#, Java, Python and C++.

~35 minIntermediateC# · Python · Java · C++
Curriculum: M34 Math · 2 of 2 lessons available

You will be able to

  • Prove that gcd(a, b) = gcd(b, a mod b) using common divisors.
  • Trace Euclid’s algorithm and state its O(log min(a, b)) bound, with consecutive Fibonacci numbers as the worst case.
  • Compute lcm(a, b) as a / gcd(a, b) · b and explain why the division comes first.
  • Handle zero and negative inputs and use the built-in gcd/lcm in each language.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

The greatest common divisor of a and b is the largest number that divides both. Trying every candidate from min(a, b) downwards takes up to min(a, b) steps, which is about a million for six-digit inputs. Euclid's algorithm needs at most a few dozen, because each step replaces the pair by a much smaller pair with exactly the same common divisors.

A picture helps: to tile a 1071 × 462 wall with the largest equal squares, cut off as many 462 × 462 squares as fit (two), leaving a 462 × 147 strip; tile that with 147-squares (three fit), leaving 147 × 21; 21-squares fill it exactly. The answer is 21. The lab's Tiles preset runs these numbers.

The algorithm

gcd(a, b):                  # a, b >= 0
    while b != 0:
        (a, b) = (b, a mod b)
    return a

Every step writes a = q · b + r with 0 ≤ r < b. The lab shows each step as a row a = q · b + r, with arrows for how b and r move one place left into the next row.

Why the step is correct

Let d divide both a and b. Then d divides r = a − q · b. Conversely, if d divides b and r, it divides a = q · b + r. So the pairs (a, b) and (b, r) have the same set of common divisors, and therefore the same greatest one. When b reaches 0 the answer is a, because every number divides 0.

If a < b, the first step has q = 0 and r = a, so it just swaps the two numbers. No special case is needed.

How many steps?

Look at two consecutive steps. If b ≤ a/2, then r < b ≤ a/2. If b > a/2, then q = 1 and r = a − b < a/2. Either way, after two steps the first number has at least halved, so the loop runs at most about 2 log₂(min(a, b)) times: O(log min(a, b)) iterations.

The worst case is when every quotient is 1, so the numbers shrink as slowly as possible. Running the algorithm backwards with all quotients equal to 1 produces the Fibonacci numbers: gcd(F(k+1), F(k)) takes k − 1 steps (Lamé's theorem, 1844). The Fibonacci preset uses 832,040 and 514,229 (F₃₀ and F₂₉): 28 steps, the most any pair below a million needs.

Each step is one division, so on fixed-size integers the total time is O(log min(a, b)). For numbers with thousands of digits each division costs more, and libraries switch to binary or Lehmer variants.

The least common multiple

lcm(a, b) is the smallest positive number both divide. Since gcd · lcm = a · b for positive a, b:

lcm(a, b) = 0 if a == 0 or b == 0
          = (a / gcd(a, b)) * b

Divide first. a · b can overflow a 64-bit integer even when the lcm fits: lcm(999983, 999979) is about 10¹², fine, but for numbers near 2⁶³ the product overflows long before the division. The division a / gcd(a, b) is always exact. Even so, the lcm itself can exceed the type, so the listings check: C# uses checked, Java Math.multiplyExact, C++ __builtin_mul_overflow (signed overflow would be undefined behaviour), and Python needs nothing.

Zero, negatives and conventions

  • gcd(a, 0) = a and gcd(0, 0) = 0 by convention (every number divides 0, so there is no largest common divisor of 0 and 0; 0 is the value that keeps the identities working).
  • lcm(a, 0) = 0.
  • For negative inputs, mathematicians take gcd(a, b) = gcd(|a|, |b|). The listings reject negative numbers instead, because % behaves differently across languages: in C#, Java and C++ the remainder takes the sign of the dividend (−7 % 3 = −1), in Python it takes the sign of the divisor (−7 % 3 = 2). Take absolute values first, and beware that |MinValue| does not fit in the type.

Euclid's algorithm and binary exponentiation share the same idea, shrinking the problem geometrically to get logarithmic step counts. Exponentiation by squaring, power(b, e) in O(log e) multiplications, is covered with a visualizer in Recursion and the call stack. Combined with mod after each multiplication it gives modular exponentiation, the core of RSA and of hashing schemes.

Built-ins

Language gcd lcm Notes
C# BigInteger.GreatestCommonDivisor none no int/long gcd in the base library; write the loop
Java BigInteger.gcd none BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)) for longs
Python math.gcd(*ints) (3.9+ accepts many) math.lcm(*ints) (3.9+) unbounded ints, negatives allowed (result is non-negative)
C++ std::gcd (C++17, <numeric>) std::lcm std::lcm is undefined if the result does not fit; it does not report overflow

The teaching implementation

Gcd / gcd and Lcm / lcm share one source file with the sieve in each language. Each language reads one shared fixture (zeros, equal numbers, a divisor pair, coprime numbers, the Fibonacci worst case, an lcm near 10¹²) and compares 3,000 random pairs with its built-in gcd (BigInteger, math.gcd, std::gcd); C# and Python also compare the first 300 with a brute-force divisor search, and C#, Java and C++ check that an lcm overflow is reported instead of wrapping.

Common mistakes

  • Multiplying before dividing in the lcm.
  • Assuming % is non-negative for negative inputs in C#, Java or C++.
  • Recursing without a base case for b = 0, or swapping the arguments the wrong way: gcd(b, a % b), not gcd(a % b, b).
  • Using the gcd of floating-point numbers: % on doubles accumulates rounding error; work with integers (scale decimals first).

Edge cases

  • One argument divides the other: one step, gcd is the smaller number.
  • a = b: one step (a mod a = 0).
  • a < b: one extra step that swaps them.
  • 1 and anything: gcd 1, lcm the other number.

Worked practice

1. Trace gcd(252, 105).

Answer

252 = 2 · 105 + 42; 105 = 2 · 42 + 21; 42 = 2 · 21 + 0. gcd = 21, after three steps. lcm = 252 / 21 · 105 = 1,260.

2. Why does gcd(a, b) never need more than about 2 log₂ b steps?

Answer

Over any two consecutive steps the larger number at least halves (either b ≤ a/2, or q = 1 and the remainder a − b < a/2), so after 2k steps it is at most min(a, b) / 2ᵏ.

3. Two buses leave the station every 12 and 18 minutes. When do they next leave together?

Answer

After lcm(12, 18) = 12 / gcd(12, 18) · 18 = 12 / 6 · 18 = 36 minutes.

Summary

  • gcd(a, b) = gcd(b, a mod b) because both pairs have the same common divisors; stop when b = 0.
  • O(log min(a, b)) steps; consecutive Fibonacci numbers are the worst case.
  • lcm = a / gcd · b, dividing first, with an overflow check in fixed-width languages.
  • Watch % with negatives; C++17 and Python ship gcd and lcm, C# and Java only for BigInteger.

Full implementation

gcd and lcm in four languages, each checked against one shared fixture (zeros, equal values, coprime pairs, the Fibonacci worst case, lcm near 10^12) and 3,000 random pairs compared with the language's own gcd (BigInteger, math.gcd, std::gcd) and a brute-force divisor search; C#, Java and C++ also check that an lcm overflow is reported.

namespace Bekadan.Dsa.Examples.Mathematics;
 
/// <summary>
/// Euclid's GCD (with LCM) and the Sieve of Eratosthenes. Built-ins:
/// <see cref="System.Numerics.BigInteger.GreatestCommonDivisor"/>; .NET has no
/// LCM or sieve in the base library.
/// </summary>
public static class NumberTheory
{
    /// <summary>gcd(a, b) for a, b ≥ 0; gcd(a, 0) = a. O(log min(a, b)) iterations.</summary>
    public static long Gcd(long a, long b)
    {
        if (a < 0 || b < 0) throw new ArgumentOutOfRangeException(nameof(a), "Use non-negative numbers.");
        while (b != 0)
        {
            (a, b) = (b, a % b);  // gcd(a, b) = gcd(b, a mod b)
        }
        return a;
    }
 
    /// <summary>lcm(a, b) for a, b ≥ 0; 0 if either is 0. Throws if the result does not fit a long.</summary>
    public static long Lcm(long a, long b)
    {
        return a == 0 || b == 0 ? 0 : checked(a / Gcd(a, b) * b);  // divide first: a * b may overflow
    }
 
    /// <summary>All primes ≤ n. O(n log log n) time, O(n) memory.</summary>
    public static List<int> Sieve(int n)
    {
        var composite = new bool[Math.Max(n + 1, 0)];  // false: still a prime candidate
        for (int p = 2; p <= n / p; p++)  // p * p <= n, written so it cannot overflow
        {
            if (composite[p]) continue;  // a smaller prime factor already marked its multiples
            for (int m = p * p; m <= n; m += p)  // k·p for k < p was marked by a factor of k
                composite[m] = true;
        }
        var primes = new List<int>();
        for (int k = 2; k <= n; k++)
            if (!composite[k]) primes.Add(k);
        return primes;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Mathematics/NumberTheory.cs

"""Euclid's GCD (with LCM) and the Sieve of Eratosthenes.
 
Built-ins: math.gcd and math.lcm (3.9+). Python ints never overflow, so
a * b // gcd would also be exact, just slower for huge numbers.
"""
 
 
def gcd(a: int, b: int) -> int:
    """gcd(a, b) for a, b >= 0; gcd(a, 0) = a. O(log min(a, b)) iterations."""
    if a < 0 or b < 0:
        raise ValueError("use non-negative numbers")
    while b != 0:
        a, b = b, a % b  # gcd(a, b) = gcd(b, a mod b)
    return a
 
 
def lcm(a: int, b: int) -> int:
    """lcm(a, b) for a, b >= 0; 0 if either is 0."""
    return 0 if a == 0 or b == 0 else a // gcd(a, b) * b  # divide first: smaller intermediate
 
 
def sieve(n: int) -> list[int]:
    """All primes <= n. O(n log log n) time, O(n) memory."""
    composite = [False] * (n + 1) if n >= 0 else []  # False: still a prime candidate
    for p in range(2, n + 1):
        if p * p > n:
            break
        if composite[p]:
            continue  # a smaller prime factor already marked its multiples
        for m in range(p * p, n + 1, p):  # k*p for k < p was marked by a factor of k
            composite[m] = True
    return [k for k in range(2, n + 1) if not composite[k]]

Tested on CPython 3.14.0 · examples/python/dsa_examples/number_theory.py

package dev.bekadan.dsa.math;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Euclid's GCD (with LCM) and the Sieve of Eratosthenes. Built-ins:
 * {@link java.math.BigInteger#gcd}; the JDK has no LCM or sieve.
 */
public final class NumberTheory {
    private NumberTheory() {
    }
 
    /** gcd(a, b) for a, b &gt;= 0; gcd(a, 0) = a. O(log min(a, b)) iterations. */
    public static long gcd(long a, long b) {
        if (a < 0 || b < 0) {
            throw new IllegalArgumentException("use non-negative numbers");
        }
        while (b != 0) {
            long r = a % b; // gcd(a, b) = gcd(b, a mod b)
            a = b;
            b = r;
        }
        return a;
    }
 
    /** lcm(a, b) for a, b &gt;= 0; 0 if either is 0. Throws ArithmeticException on overflow. */
    public static long lcm(long a, long b) {
        return a == 0 || b == 0 ? 0 : Math.multiplyExact(a / gcd(a, b), b); // divide first: a * b may overflow
    }
 
    /** All primes &lt;= n. O(n log log n) time, O(n) memory. */
    public static List<Integer> sieve(int n) {
        boolean[] composite = new boolean[Math.max(n + 1, 0)]; // false: still a prime candidate
        for (int p = 2; p <= n / p; p++) { // p * p <= n, written so it cannot overflow
            if (composite[p]) {
                continue; // a smaller prime factor already marked its multiples
            }
            for (int m = p * p; m <= n; m += p) { // k*p for k < p was marked by a factor of k
                composite[m] = true;
            }
        }
        List<Integer> primes = new ArrayList<>();
        for (int k = 2; k <= n; k++) {
            if (!composite[k]) {
                primes.add(k);
            }
        }
        return primes;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/math/NumberTheory.java

#pragma once
 
#include <cstdint>
#include <stdexcept>
#include <vector>
 
namespace bekadan::dsa {
 
// Euclid's GCD (with LCM) and the Sieve of Eratosthenes.
// Built-ins: std::gcd and std::lcm in <numeric> (C++17); std::lcm does not
// report overflow (the result is undefined if it does not fit).
 
// gcd(a, b) for a, b >= 0; gcd(a, 0) = a. O(log min(a, b)) iterations.
inline std::int64_t gcd(std::int64_t a, std::int64_t b) {
    if (a < 0 || b < 0) throw std::invalid_argument("use non-negative numbers");
    while (b != 0) {
        const std::int64_t r = a % b;  // gcd(a, b) = gcd(b, a mod b)
        a = b;
        b = r;
    }
    return a;
}
 
// lcm(a, b) for a, b >= 0; 0 if either is 0. Throws instead of overflowing
// (signed overflow would be undefined behaviour).
inline std::int64_t lcm(std::int64_t a, std::int64_t b) {
    if (a == 0 || b == 0) return 0;
    std::int64_t result = 0;
    if (__builtin_mul_overflow(a / gcd(a, b), b, &result)) throw std::overflow_error("lcm does not fit in 64 bits");
    return result;  // divide first: a * b may overflow even when the lcm fits
}
 
// All primes <= n. O(n log log n) time, O(n) memory (std::vector<bool> packs bits).
inline std::vector<int> sieve(int n) {
    std::vector<bool> composite(n >= 0 ? static_cast<std::size_t>(n) + 1 : 0, false);  // false: still a candidate
    for (int p = 2; p <= n / p; ++p) {  // p * p <= n, written so it cannot overflow
        if (composite[static_cast<std::size_t>(p)]) continue;  // a smaller prime factor already marked its multiples
        for (int m = p * p; m <= n; m += p) composite[static_cast<std::size_t>(m)] = true;  // k*p for k < p is done
    }
    std::vector<int> primes;
    for (int k = 2; k <= n; ++k)
        if (!composite[static_cast<std::size_t>(k)]) primes.push_back(k);
    return primes;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/number_theory.hpp

References