Extended Euclidean algorithm, Euclidean Algorithm
2016.1.25
(Not updated)
1. Euclidean Algorithm (moving phase Division)
1. Purpose: quickly calculate the maximum number of common approx.
2. essence: gcd (a, B) = gcd (B, a % B)
3. Proof: If r = a mod B is set, we need to prove that gcd (a, B) = gcd (B, r)
If gcd (a, B) is set to c, a = mc, B = nc, and m, n are mutually qualitative. So r = a-kb = (m-kn) c, so c is also the factor of r.
If gcd (B, r)> c is set to d, B = m1 * d, r = n1 * d, so a = (m1 + n1) * d, then d is the factor of a, so gcd (a, B) = d, which is inconsistent with the question.
Therefore, gcd (a, B) = gcd (B, r)
4. Time Complexity: Obviously, after two recursion, the first parameter is reduced by at least half.
Therefore, the time complexity is roughly O (log max (a, B ))
5. Typical Example: Number of vertices on a line segment
Ii. Extended Euclidean Algorithm:
1. Purpose: quickly calculate the integer x and y so that ax + by = gcd (a, B)
2. essence code:
void extgcd(int a,int b,int &x,int &y){ if(!b) { x=1;y=0; return a; } else { extgcd(b,a%b,y,x); y-=(a/b)*x; }}
3. Proof: Since gcd (a, B) = gcd (B, a % B)
So B * x1 + (a % B) * y1 = gcd (a, B)
A % B = a-(a/B) * B
Therefore, gcd (a, B) = B * x1 + (a-(a/B) * y1
= B * x1 + a * y1-(a/B) * B * y1
= A * y1 + B * (x1-a/B * y1)
For the x, y we want to make ax + by = gcd (a, B)
X = y1
Y = x1-a/B * y1
Certificate completion
As for the termination condition, when the Euclidean Algorithm terminates, a = gcd, B = 0, then when x = 1, y = 0, the target formula is required.
In addition, for the mandatory and sufficient condition of ax + by = c, why is c = gcd (a, B), you can Baidu's Yi Shu theorem.
4. Time Complexity: Consistent with euclidean Algorithm
5. Typical Example: Double Six