Algorithm Summary-Euclidean Algorithm
1. Euclidean Algorithm
Euclidean algorithm, also known as the moving phase division, is used to calculate the maximum approximate number of two positive integers A and B.
The computation principle depends on the following theorem:
Gcd (a, B) = gcd (B, A mod B) (A> B and A mod B is not 0)
Code implementation:
1 int gcd(int a,int b)2 {3 return b==0?a:gcd(b,a%b);4 }
2. Extended Euclidean Algorithm
Basic Algorithms:
For non-negative integers a, B, gcd (A, B) with an incomplete value of 0, it indicates the maximum approximate number of A and B. There must be an integer pair X and Y, making gcd (A, B) = AX +.
Proof:
Let's assume that a positive integer of the equation AX + by = gcd (a, B) = D is interpreted as X1, Y1. Do not doubt that this equation must have a solution.
Then ax1 + by1 = gcd (A, B) (1)
For the equation bx + (a % B) y = gcd (B, A % B), there is a solution X2, Y2 (hypothesis)
Bx2 + (a % B) y2 = gcd (B, A % B) = gcd (A, B) (2)
And a % B = A-(A/B) * B;
Then the formula (2) is changed to bx2 + (a-(A/B) * B) y2 = gcd (A, B );
That is, ay2 + B (x2-(A/B) * Y2) = gcd (a, B) (3 );
Comparison (1) (3)
X1 = Y2; Y1 = x2-(A/B) * Y2
Therefore, the solution of AX + by = gcd (a, B) only needs to be in the equation bx + (a % B) y = gcd (B, A % B) on the basis of the original equation,
Because GCD always recurs When B = 0, the solution of the equation can be obtained through recursion.
Code implementation:
1 LL extended_gcd (ll a, LL B, ll & X, ll & Y) // The returned value is gcd (a, B) 2 {3 LL ret, TMP; 4 If (B = 0) 5 {6 x = 1, y = 0; 7 return a; 8} 9 ret = extended_gcd (B, A % B, X, y); 10 TMP = x; 11 x = y; 12 y = TMP-A/B * Y; 13 return ret; 14}
3. Some conclusions
1) The Equation AX + by = C meets the condition: c = K * gcd (A, B) (k is an integer), then the equation has an integer solution. Otherwise, there is no solution.
2) Set A, B, and C to any integer. If a group of integers in the equation AX + by = C is interpreted as (x0, y0), any integer solution of it can be written as (x0 + kb ', y0-ka '), here, A' = A/gcd (a, B), B '= B/gcd (a, B), and K are any integers.
3) if a group of Integer Solutions (x1, x2) is set to X0 = x1 % B 'Y0 = Y1 % B', x0 and Y0 are the closest to zero solutions.