Algorithm · Bits and math · O(log min(a, b))
Euclid’s GCD
The greatest common divisor by repeated remainders, gcd(a, b) = gcd(b, a mod b), in O(log min(a, b)) steps; the LCM follows from it.
The full derivation, edge cases and exercises are in the lesson Euclid’s algorithm: GCD and LCM. Open it full width in the playground.
On this page
The idea
Any common divisor of a and b also divides a mod b, so replacing (a, b) with (b, a mod b) keeps the same set of common divisors while the numbers shrink. When the remainder reaches 0, the other number is the GCD.
The remainder at least halves every two steps, which bounds the loop logarithmically; consecutive Fibonacci numbers are the worst case (Lamé’s theorem). lcm(a, b) = a / gcd(a, b) · b, dividing first so the intermediate stays small.
Steps
- While b ≠ 0: (a, b) ← (b, a mod b).
- Return a.
- For the LCM, compute a / gcd · b.
Invariants
What holds at every step; the correctness argument rests on these.
- gcd(a, b) is the same before and after every step.
- b strictly decreases, so the loop ends.
Complexity
| Case | Time | Extra space |
|---|---|---|
| GCD or LCM | O(log min(a, b)) | O(1) iterative |
When to use it
Use it when
- Reducing fractions, aligning periods (LCM), checking whether two numbers are coprime.
Avoid it when
- The standard library already has it: Math.gcd in Python, BigInteger.gcd in Java, std::gcd and std::lcm in C++.
Step through it
The interactive lab for euclid’s gcd: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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 >= 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 >= 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 <= 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
Learn more
Lessons
- Euclid’s algorithm: GCD and LCM· M34 Math
Problems, patterns and exercises
- ProblemThe largest tile that fits both walls· beginner · O(log min(a, b)) iterations
- PatternBit tricks and arithmetic invariants· O(n) scans; O(set bits) popcount; O(log min(a, b)) gcd