{
    "slug": "euclidean_algorithm",
    "term": "Euclidean Algorithm",
    "category": "algorithms",
    "difficulty": "beginner",
    "short": "An ancient method for computing the greatest common divisor of two integers by repeatedly taking remainders until one becomes zero.",
    "long": "The Euclidean algorithm finds the greatest common divisor (GCD) of two non-negative integers based on the principle that gcd(a, b) equals gcd(b, a mod b). You repeatedly replace the pair (a, b) with (b, a mod b) until the second value reaches zero; the remaining non-zero value is the GCD. It runs in O(log min(a, b)) time because each step reduces the operands by at least a constant factor (the Fibonacci numbers are the worst case). The algorithm can be written recursively or iteratively, and the iterative form avoids any stack-depth concerns for large inputs.\n\nThe original subtraction-based form repeatedly subtracts the smaller value from the larger, but this degrades to O(a) when one operand is much larger - the modulo form fixes that by collapsing many subtractions into a single division. The extended Euclidean algorithm additionally computes integer coefficients x and y such that a*x + b*y = gcd(a, b), which is the foundation of modular inverses used in RSA and other cryptographic schemes.\n\nPractical uses include reducing fractions to lowest terms, computing the least common multiple via lcm(a, b) = a / gcd(a, b) * b, checking coprimality, and clock or modular arithmetic. Because it relies only on integer remainders, it works for arbitrarily large integers as long as your language supports big integers; PHP's intdiv and modulo operators handle 64-bit values, and the GMP extension handles bignums.\n\nCommon pitfalls involve negative inputs (take absolute values first), the zero edge case (gcd(0, 0) is conventionally 0, and gcd(n, 0) is n), and integer overflow when computing the LCM by multiplying before dividing. Keeping the operands ordered is unnecessary because the first modulo step automatically swaps them.",
    "aliases": [
        "gcd algorithm",
        "greatest common divisor",
        "euclid gcd"
    ],
    "tags": [
        "algorithms",
        "number-theory",
        "gcd",
        "modular-arithmetic",
        "recursion"
    ],
    "misconception": "Many believe you must order the inputs so the larger comes first. The first modulo step swaps them automatically, so order does not matter.",
    "why_it_matters": "GCD computation underpins fraction reduction, LCM, modular inverses, and RSA key math, and the algorithm is so fast (logarithmic) that it is the default tool wherever exact integer ratios are needed.",
    "common_mistakes": [
        "Using repeated subtraction instead of modulo, which becomes O(a) for very unequal operands.",
        "Forgetting to take absolute values, producing wrong results for negative inputs.",
        "Computing LCM as a * b / gcd, which overflows before dividing instead of a / gcd * b.",
        "Mishandling the zero case where gcd(n, 0) should return n.",
        "Writing deep recursion for huge inputs when an iterative loop avoids stack growth."
    ],
    "when_to_use": [
        "Reducing fractions to lowest terms by dividing numerator and denominator by their GCD.",
        "Computing LCM, checking coprimality, or working with modular arithmetic.",
        "Deriving modular inverses via the extended Euclidean algorithm for cryptographic math.",
        "Any time you need an exact integer ratio between two quantities quickly."
    ],
    "avoid_when": [
        "You need the GCD of polynomials or non-integer values, where a specialised algorithm applies.",
        "Inputs exceed 64-bit range and you are not using a bignum library like GMP, risking overflow.",
        "A language built-in such as gmp_gcd or math.gcd already provides a tested, optimised implementation."
    ],
    "related": [
        "recursion_patterns",
        "bit_manipulation",
        "big_o_notation",
        "divide_and_conquer"
    ],
    "prerequisites": [
        "big_o_notation",
        "recursion_patterns",
        "php_data_types"
    ],
    "refs": [
        "https://en.wikipedia.org/wiki/Euclidean_algorithm",
        "https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm"
    ],
    "bad_code": "// Subtraction form - O(a) when operands are very unequal:\nfunction gcd(int $a, int $b): int {\n    while ($a !== $b) {\n        if ($a > $b) {\n            $a -= $b;   // gcd(1000000, 1) loops ~1,000,000 times\n        } else {\n            $b -= $a;\n        }\n    }\n    return $a; // also breaks if either input is 0\n}",
    "good_code": "// Modulo form - O(log min(a,b)), handles negatives and zero:\nfunction gcd(int $a, int $b): int {\n    $a = abs($a);\n    $b = abs($b);\n    while ($b !== 0) {\n        [$a, $b] = [$b, $a % $b]; // first step swaps automatically\n    }\n    return $a; // gcd(n, 0) returns n\n}\n\nfunction lcm(int $a, int $b): int {\n    if ($a === 0 || $b === 0) return 0;\n    return intdiv(abs($a), gcd($a, $b)) * abs($b); // divide before multiply\n}",
    "quick_fix": "Replace repeated subtraction with the modulo form gcd(a,b)=gcd(b, a mod b) and take absolute values up front.",
    "severity": "low",
    "effort": "low",
    "created": "2026-06-13",
    "updated": "2026-06-13",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/euclidean_algorithm",
        "html_url": "https://codeclaritylab.com/glossary/euclidean_algorithm",
        "json_url": "https://codeclaritylab.com/glossary/euclidean_algorithm.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Euclidean Algorithm](https://codeclaritylab.com/glossary/euclidean_algorithm) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/euclidean_algorithm"
            }
        }
    }
}