Extended Euclid's theorem for the solution of the equation ax + by = gcd (a, b)
int Exgcd(int a, int b, int &x, int &y) { if (!b) { x = 1; y = 0; return a; } int d = Exgcd(b, a % b, x, y); int t = x; x = y; y = t - (a / b) * y; return d; }
See proof: https://oi-wiki.org/math/gcd/
By constructing the equivalent equation Euclid's theorem, a recursive solution;
Linear congruent equation:
Shaped like ax ≡ c (mod b) of the equation;
1. equivalent: equivalent to ax + by = c, on both sides at the same time as the modulo
2. determination condition: ax by Solution + = gcd (a, b) of exgcd can be evaluated, so that c is gcd (a, b) is an integer multiple of, when AX + by = c solvable equation
3. General Solution: After solving the general solution can be configured according to the original equation: x + k * b / gcd, y - k * a / gcd
4. The smallest positive integer solutions: The general solution in the form of solutions available smallest positive integer x is (x% t + t)% t, t = b / gcd;
int ex_gcd(int a, int b, int& x, int& y) { if (b == 0) { x = 1; y = 0; return a; } int d = ex_gcd(b, a % b, x, y); int temp = x; x = y; y = temp - a / b * y; return d; } bool liEu(int a, int b, int c, int& x, int& y) { int d = ex_gcd(a, b, x, y); if (c % d != 0) return 0; int k = c / d; x *= k; y *= k; return 1; }