Bits / math · O(log min(a, b))

Euclid's GCD

(a, b) ← (b, a mod b) until b = 0, then lcm = a / gcd · b.

The full explanation, derivation and practice are in the lesson Euclid’s algorithm: GCD and LCM.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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