The atmosphere at the W50 Taizhou China is electrifying, with passionate fans filling the stands to support their favorite players. The unique blend of culture and sports creates an unforgettable experience for both players and spectators.
Fan Interaction and Community Building
yaolei2046/leetcode-python<|file_sep|>/classical-algorithms/extended-euklidian.md
# Extended Euclidean Algorithm [TOC] ## Problem Description Given two positive integers `a` and `b`, we want to find integers `x` `y` such that `ax` `+` `by` = `gcd(a,b)`. ## The Algorithm The proof of this algorithm is based on induction. ### The idea Given `d = gcd(a,b)`, we have both `a` % `d` = 0 and `b` % `d` = 0. #### Proof 1. Because `d = gcd(a,b)`, `d` | `a` so there exists an integer `k` such that `a` = `dk`
2. Similarly, because `d = gcd(a,b)`, `d` | `b` so there exists an integer `m` such that `b` = `dm`
3. So we have:
ax + by = (dk)x + (dm)y
= d(kx + my) ### Why "extend" Now recall that we also have another equation which is our original Euclidean algorithm: r[i] = r[i-2] - q[i-1]*r[i-1] # here we know r[i] = gcd(r[i-2],r[i-1])
# we only need show r[i] = gcd(r[i-2],r[i-1]), r[i] | r[i-2] and r[i] | r[i-1]. Now we have known `r[i]` | `r[i-2]` and `r[i]` | `r[i-1]`, so r[2] % r[0] = 0
r[3] % r[1] = 0
r[4] % r[2] = 0
...
r[i] % r[i-2] = 0
r[i] % r[i-1] = 0
=> r[i-2] = k*r[i]
=> r[i-1] = m*r[i] So we know: ax + by = (r[i-2])x + (r[i-1])y
= (k*r[i])x + (m*r[i])y
= r[i] * (kx + my) where we need find what `x` is, `y` is. So we set: x = p[i] = (prev_p - (q[i-1] * prev_q))
y = p[i-1] Then we get: ax + by
= (r[i-2])x + (r[i-1])y
= k * r[i] * p[i] + m * r[i] * p[i-1]
= r[i] * (k * p[i] + m * p[i-1]) so that since `ax` `+` `by` = `gcd(a,b)`, we have `k * p[i] + m * p[i-1]` must be equal to 1. # note about x, y we set: # p2 = 1
# p1 = 0
# p(i) = prev_p - q(i-1) * prev_q # q2 = 0
# q1 = 1
# q(i) = prev_q # so when i = 2: p(i) = p2 - q1 * q2 = 1 - 1 * 0 = 1
# when i = 3: p(i) = p3 - q2 * q3 = 0 - 0 * 1 = 0
# when i = 4: p(i) = p4 - q3 * q4 = 1 - 1 * 2 = -1
# when i = 5: p(i) = p5 - q4 * q5 = 0 - 2 * 3 = -6
# when i = 6: p(i) = p6 - q5 * q6 = -1 - 3 * 5 = -16 We set some initial value such that following that rule will give the right result. ### Code Python def gcd(a,b):
return b if a % b == 0 else gcd(b,a % b) def egcd(a,b):
prev_q, q = None,None
prev_p,p = (1,0),(0,1)
while b != 0:
quotient = a // b
a,b = b,a % b
prev_q,q = q,quotient
prev_p,p = p,(prev_p - (q * prev_p))
return (a,p[0])
for i in range(2,30):
x,y = egcd(i,i+1)
print("d: " + str(x) + " = " + str((i * y) + ((i+1) * (-(y-1))))) Note: Our `x`, `