{
  "id": "extended-euclidean-algorithm",
  "title": "Extended Euclidean Algorithm",
  "lang": "en",
  "source_lang": "en",
  "summary": "The extended Euclidean algorithm computes the greatest common divisor of two integers together with coefficients expressing that divisor as their integer linear combination.",
  "category": "mathematics",
  "subcategory": "algebra",
  "type": "concept",
  "aliases": [
    "Extended Euclid's algorithm",
    "Extended GCD algorithm",
    "XGCD"
  ],
  "generated_at": "2026-11-05",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/extended-euclidean-algorithm/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/extended-euclidean-algorithm/",
      "json": "https://aiwiki.page/zh/extended-euclidean-algorithm.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "The extended Euclidean algorithm is an algorithm that, given two integers \\(a\\) and \\(b\\), computes their nonnegative greatest common divisor \\(d\\) and integers \\(x,y\\) such that\n\n\\[ax+by=d=\\gcd(a,b).\\]\n\nIt extends the Euclidean algorithm by tracking how each successive remainder can be expressed in terms of the original inputs. The resulting coefficients, called Bézout coefficients, provide a constructive form of Bézout's identity. The method is fundamental in computational number theory, especially for finding modular inverses and solving integer equations."
    },
    {
      "heading": "Mathematical basis",
      "text": "For nonnegative integers \\(a,b\\) with \\(b>0\\), division with remainder gives\n\n\\[a=qb+r,\\qquad 0\\le r<b.\\]\n\nThe key identity is\n\n\\[\\gcd(a,b)=\\gcd(b,r).\\]\n\nIndeed, an integer divides both \\(a\\) and \\(b\\) if and only if it divides both \\(b\\) and \\(a-qb\\).\n\nRepeated division therefore produces a sequence of decreasing nonnegative remainders. The last nonzero remainder is the greatest common divisor.\n\nThe extended algorithm adds an observation: every new remainder is an integer linear combination of the previous two. Since the initial values are already linear combinations of \\(a\\) and \\(b\\),\n\n\\[a=1a+0b,\\qquad b=0a+1b,\\]\n\nevery later remainder can also be expressed as \\(sa+tb\\). Tracking the coefficients eventually expresses the greatest common divisor in this form.\n\nThe underlying division procedure appears in Books VII and X of Euclid's Elements, for integers and magnitudes respectively. The extended procedure retains the same divisions while adding coefficient bookkeeping."
    },
    {
      "heading": "Recurrence and implementation",
      "text": "For positive inputs, initialize\n\n\\[(r_0,s_0,t_0)=(a,1,0),\\qquad (r_1,s_1,t_1)=(b,0,1).\\]\n\nAt each step, compute\n\n\\[q_i=\\left\\lfloor\\frac{r_{i-1}}{r_i}\\right\\rfloor\\]\n\nand update\n\n\\[\\begin{aligned} r_{i+1}&=r_{i-1}-q_i r_i,\\\\ s_{i+1}&=s_{i-1}-q_i s_i,\\\\ t_{i+1}&=t_{i-1}-q_i t_i. \\end{aligned}\\]\n\nThese recurrence relations preserve\n\n\\[r_i=s_i a+t_i b.\\]\n\nWhen the next remainder is zero, the current nonzero remainder and its coefficients give the answer.\n\nThe following iterative version handles negative inputs by applying the divisions to their absolute values:\n\nextended_gcd(a, b):\n    old_r, r = abs(a), abs(b)\n    old_s, s = 1, 0\n    old_t, t = 0, 1\n\n    while r != 0:\n        q = old_r // r\n\n        old_r, r = r, old_r - q*r\n        old_s, s = s, old_s - q*s\n        old_t, t = t, old_t - q*t\n\n    if a < 0:\n        old_s = -old_s\n    if b < 0:\n        old_t = -old_t\n\n    return old_r, old_s, old_t\n\nEach paired assignment is simultaneous: both right-hand expressions use the values from before the assignment.\n\nFor a single zero input, the procedure returns the absolute value of the other input and suitable coefficients. Under the common convention \\(\\gcd(0,0)=0\\), it also returns a valid identity for \\((0,0)\\), although some treatments leave that greatest common divisor undefined."
    },
    {
      "heading": "Worked example",
      "text": "For \\(a=240\\) and \\(b=46\\), the Euclidean divisions are\n\n\\[\\begin{aligned} 240&=5\\cdot46+10,\\\\ 46&=4\\cdot10+6,\\\\ 10&=1\\cdot6+4,\\\\ 6&=1\\cdot4+2,\\\\ 4&=2\\cdot2+0. \\end{aligned}\\]\n\nThus \\(\\gcd(240,46)=2\\).\n\nTracking coefficients gives:\n\nRemainder \\(r\\) | Coefficient \\(s\\) of \\(240\\) | Coefficient \\(t\\) of \\(46\\)\n\\(240\\) | \\(1\\) | \\(0\\)\n\\(46\\) | \\(0\\) | \\(1\\)\n\\(10\\) | \\(1\\) | \\(-5\\)\n\\(6\\) | \\(-4\\) | \\(21\\)\n\\(4\\) | \\(5\\) | \\(-26\\)\n\\(2\\) | \\(-9\\) | \\(47\\)\n\nThe output is therefore\n\n\\[(d,x,y)=(2,-9,47),\\]\n\nwith\n\n\\[240(-9)+46(47)=2.\\]\n\nThe same coefficients can be found by back-substitution, starting at the last nonzero remainder:\n\n\\[\\begin{aligned} 2 &=6-4\\\\ &=6-(10-6)\\\\ &=2(46-4\\cdot10)-10\\\\ &=2\\cdot46-9(240-5\\cdot46)\\\\ &=-9\\cdot240+47\\cdot46. \\end{aligned}\\]\n\nBack-substitution and forward coefficient tracking are two implementations of the same algebraic process."
    },
    {
      "heading": "Correctness",
      "text": "Correctness follows from three properties.\n\nPreservation of the greatest common divisor. Each replacement\n\n\\[(u,v)\\longmapsto(v,u-qv)\\]\n\nleaves the common divisors unchanged.\n\nPreservation of the coefficient identity. If\n\n\\[u=sa+tb,\\qquad v=s'a+t'b,\\]\n\nthen\n\n\\[u-qv=(s-qs')a+(t-qt')b.\\]\n\nThus every stored remainder has the claimed representation.\n\nTermination. The nonzero remainders form a strictly decreasing sequence of positive integers, so eventually a remainder is zero.\n\nAt termination, the last nonzero remainder has the same greatest common divisor as the inputs and is itself that divisor. Its stored coefficients establish the required identity.\n\nMatrix interpretation\n\nA single update can also be written using a matrix:\n\n\\[\\begin{pmatrix} r_i\\\\ r_{i+1} \\end{pmatrix} = \\begin{pmatrix} 0&1\\\\ 1&-q_i \\end{pmatrix} \\begin{pmatrix} r_{i-1}\\\\ r_i \\end{pmatrix}.\\]\n\nThe update matrix has determinant \\(-1\\), so its inverse also has integer entries. Applying the same matrix to the coefficient rows explains why remainder computation and coefficient tracking stay synchronized."
    },
    {
      "heading": "Applications",
      "text": "Modular inverses\n\nIn modular arithmetic, an integer \\(a\\) has a multiplicative inverse modulo \\(m>1\\) exactly when\n\n\\[\\gcd(a,m)=1.\\]\n\nIf the algorithm finds\n\n\\[ax+my=1,\\]\n\nthen reduction modulo \\(m\\) gives\n\n\\[ax\\equiv1\\pmod m.\\]\n\nThus \\(x\\bmod m\\) is an inverse of \\(a\\).\n\nFor example,\n\n\\[17(-5)+43(2)=1,\\]\n\nso the inverse of \\(17\\) modulo \\(43\\) is\n\n\\[-5\\bmod43=38.\\]\n\nIf the computed gcd exceeds \\(1\\), no inverse exists.\n\nModular inversion is used in computational algebra and cryptography, including arithmetic underlying public-key systems.\n\nLinear Diophantine equations\n\nA linear Diophantine equation\n\n\\[ax+by=c\\]\n\nwith \\(a,b\\) not both zero has an integer solution if and only if\n\n\\[d=\\gcd(a,b)\\]\n\ndivides \\(c\\).\n\nIf the algorithm gives\n\n\\[ax_0+by_0=d,\\]\n\nthen one solution is\n\n\\[x_p=x_0\\frac{c}{d},\\qquad y_p=y_0\\frac{c}{d}.\\]\n\nAll integer solutions are\n\n\\[x=x_p+\\frac{b}{d}k,\\qquad y=y_p-\\frac{a}{d}k,\\qquad k\\in\\mathbb Z.\\]\n\nIn particular, Bézout coefficients are generally not unique. For \\(c=d\\), this formula describes all coefficient pairs representing the gcd.\n\nCongruences and the Chinese remainder theorem\n\nA congruence\n\n\\[ax\\equiv c\\pmod m\\]\n\nis equivalent to an integer equation\n\n\\[ax+my=c.\\]\n\nThe extended algorithm therefore determines whether it is solvable and constructs solutions.\n\nIt also supplies the modular inverses used in constructive proofs and implementations of the Chinese remainder theorem. For noncoprime moduli, a gcd calculation determines whether the congruences are compatible."
    },
    {
      "heading": "Efficiency and implementation limitations",
      "text": "Let\n\n\\[n=\\left\\lceil\\log_2(\\max(|a|,|b|)+1)\\right\\rceil\\]\n\nmeasure the input size in bits. The standard algorithm uses \\(O(n)\\) Euclidean division steps, expressed in big-O notation. Consecutive members of the Fibonacci sequence give worst-case division counts for a given input magnitude.\n\nThe division count is not the same as the bit-operation cost. With classical integer arithmetic, a standard implementation has \\(O(n^2)\\) bit complexity. Faster divide-and-conquer variants can achieve bounds of the form\n\n\\[O(M(n)\\log n),\\]\n\nwhere \\(M(n)\\) denotes the cost of multiplying \\(n\\)-bit integers.\n\nThe iterative implementation stores only a fixed number of integers, but their bit lengths grow with the input size; its storage is therefore not constant when measured in bits.\n\nPractical limitations include:\n\n- Overflow: intermediate coefficient products can exceed a fixed-width integer type even when the final result fits.\n- Signed division conventions: using nonnegative remainders avoids differences between programming languages' rules for negative division.\n- Timing leakage: the ordinary algorithm's iteration count and branches depend on its inputs. Cryptographic uses involving secrets may require specialized constant-time implementations."
    },
    {
      "heading": "Generalizations",
      "text": "The method extends beyond integers to a Euclidean domain, where division with a suitably decreasing remainder measure is available.\n\nAn important example is the ring of polynomials over a field. Given polynomials \\(f\\) and \\(g\\), the extended algorithm computes polynomials \\(u,v,d\\) satisfying\n\n\\[uf+vg=d,\\]\n\nwhere \\(d\\) is a greatest common divisor. Since polynomial gcds are determined only up to multiplication by a nonzero field element, they are usually normalized to be monic.\n\nIf \\(p\\) is irreducible and \\(f\\) is not divisible by \\(p\\), normalizing the identity to\n\n\\[uf+vp=1\\]\n\nmakes \\(u\\) an inverse of \\(f\\) modulo \\(p\\). This provides an effective inversion method in polynomial representations of finite fields.\n\nThe existence of a gcd alone does not guarantee that the extended procedure applies in an arbitrary ring: the Euclidean algorithm additionally requires a suitable division-with-remainder operation."
    }
  ],
  "links": [
    "algorithm",
    "integer",
    "greatest-common-divisor",
    "euclidean-algorithm",
    "bezouts-identity",
    "number-theory",
    "linear-combination",
    "euclids-elements",
    "recurrence-relation",
    "absolute-value",
    "matrix",
    "determinant",
    "modular-arithmetic",
    "modular-multiplicative-inverse",
    "cryptography",
    "diophantine-equation",
    "chinese-remainder-theorem",
    "big-o-notation",
    "fibonacci-sequence",
    "polynomial",
    "field-mathematics",
    "finite-field"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}