Algorithm Summary-Euclidean Algorithm
Euclidean algorithms 1. Euclidean algorithms the Euclidean algorithm is also known as the moving phase division. It is used to calculate the maximum approximate numbers of two positive integers a and B. The calculation 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 basic Euclidean Algorithm: for non-negative integers a, B, gcd (a, B) with an incomplete value of 0, they represent the maximum common approx. There must be an integer pair of x, y, make gcd (a, B) = ax +. Proof: Let's first assume that a positive integer of the equation ax + by = gcd (a, B) = d is interpreted as x1, y1; no doubt, this equation must have solutions: ax1 + by1 = gcd (a, B) (1) and for equation bx + (a % B) y = gcd (B, a % B) if there is a solution x2, y2 (assuming) Then bx2 + (a % B) y2 = gcd (B, a % B) = gcd (a, B) (2) and a % B = a-(a/B) * B; then (2) is changed to bx2 + (a-(a/B) * B) y2 = gcd (, b); that is, ay2 + B (x2-(a/B) * y2) = gcd (a, B) (3); comparison (1) (3) obtain x1 = y2; y1 = x2-(a/B) * y2. Therefore, ax + by = gcd (a, B) you only need to perform a simple operation on the basis of the solution of the equation bx + (a % B) y = gcd (B, a % B) to convert it into the solution of the original equation, because gcd always recurs When B = 0, the solution of the equation can be obtained through recursion. Code implementation: Copy code 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} copy code 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.