The Extended Euclidean Algorithm computes integers x, y such that ax + by = gcd(a, b).
BASIS: When b = 0, gcd(a, 0) = a, and a1 + 00 = a. So x=1, y=0.
RECURSIVE STEP: Given gcd(b, a mod b) returns (g, x', y') where b*x' + (a mod b)*y' = g.
Substitute a mod b = a - floor(a/b)b:
bx' + (a - floor(a/b)b)y' = g
ay' + b(x' - floor(a/b)*y') = g
So x = y', y = x' - floor(a/b)*y'.
Iterative version (avoids recursion stack):
old_r = a, r = b; old_s = 1, s = 0; old_t = 0, t = 1
while r != 0:
q = old_r / r
(old_r, r) = (r, old_r - qr)
(old_s, s) = (s, old_s - qs)
(old_t, t) = (t, old_t - q*t)
return old_r, old_s, old_t // gcd, x, y
Example: a=35, b=15
35 = 215 + 5, 15 = 35 + 0. gcd=5.
Back-substitute: 5 = 35 - 215. So x=1, y=-2.
Verify: 351 + 15*(-2) = 35 - 30 = 5. Correct.
SIGN PROPERTY: gcd(a,b) = ax + by. x can be negative (y positive or vice versa). To get positive x: x += b/g, y -= a/g.
UNIQUENESS: Solutions form a family: x' = x + k*(b/g), y' = y - k*(a/g) for any integer k. The algorithm returns the solution with |x| <= b/(2g) and |y| <= a/(2g) (nearly minimal).
COMPLEXITY: O(log(min(a,b))) steps. Each step is O(1) arithmetic on machine words. For big integers, O(M(n) * log(min(a,b))) where M(n) is multiplication time.