← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

Euclidean Algorithm

Algorithms PHP 7.1+ Beginner
debt(d7/e2/b2/t4)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7), because detection_hints.automated is 'no' and the only signal is a code_pattern (subtraction loop instead of modulo); no automated tooling flags it, so a reviewer or performance test on unequal operands surfaces it.

e2 Effort Remediation debt — work required to fix once spotted

Closest to 'one-line patch or single-call swap' (e1), nudged to e2 because quick_fix is replacing repeated subtraction with the modulo form gcd(a,b)=gcd(b, a mod b) plus taking absolute values up front — essentially a tiny localized edit slightly above a pure one-liner.

b2 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3), nudged down to b2 because the algorithm is a self-contained utility function; though applies_to spans web/cli/library, a GCD helper imposes little gravitational pull on future maintainers and is easily swapped.

t4 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'minor surprise (one edge case)' (t3), nudged to t4 because the misconception (that inputs must be ordered largest-first, when the first modulo step swaps them automatically) is a genuine but recoverable surprise, compounded by documented gotchas like the gcd(n,0) zero case and negative inputs.

About DEBT scoring →

Also Known As

gcd algorithm greatest common divisor euclid gcd

TL;DR

An ancient method for computing the greatest common divisor of two integers by repeatedly taking remainders until one becomes zero.

Explanation

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.

The 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.

Practical 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.

Common 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.

Diagram

flowchart TD
    START[gcd a=48 b=18] --> S1[48 mod 18 = 12<br/>now gcd 18,12]
    S1 --> S2[18 mod 12 = 6<br/>now gcd 12,6]
    S2 --> S3[12 mod 6 = 0<br/>now gcd 6,0]
    S3 --> DONE[b is 0<br/>GCD = 6]
style DONE fill:#238636,color:#fff
style START fill:#1f6feb,color:#fff

Common 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.

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.

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.

Code Examples

✗ Vulnerable
// Subtraction form - O(a) when operands are very unequal:
function gcd(int $a, int $b): int {
    while ($a !== $b) {
        if ($a > $b) {
            $a -= $b;   // gcd(1000000, 1) loops ~1,000,000 times
        } else {
            $b -= $a;
        }
    }
    return $a; // also breaks if either input is 0
}
✓ Fixed
// Modulo form - O(log min(a,b)), handles negatives and zero:
function gcd(int $a, int $b): int {
    $a = abs($a);
    $b = abs($b);
    while ($b !== 0) {
        [$a, $b] = [$b, $a % $b]; // first step swaps automatically
    }
    return $a; // gcd(n, 0) returns n
}

function lcm(int $a, int $b): int {
    if ($a === 0 || $b === 0) return 0;
    return intdiv(abs($a), gcd($a, $b)) * abs($b); // divide before multiply
}

Added 13 Jun 2026
Views 16
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 2 pings S 0 pings M 0 pings T 2 pings W 1 ping T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W
No pings yet today
No pings yesterday
Google 3 Ahrefs 1 Perplexity 1 SEMrush 1 PetalBot 1
crawler 6 crawler_json 1
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Replace repeated subtraction with the modulo form gcd(a,b)=gcd(b, a mod b) and take absolute values up front.
📦 Applies To
PHP 7.1+ web cli library
🔗 Prerequisites
🔍 Detection Hints
while loop subtracting one variable from another to find a common divisor instead of using modulo
Auto-detectable: ✗ No
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✗ Manual fix Fix: Low Context: Function Tests: Update


✓ schema.org compliant