Extended Euclidean algorithm, Euclidean Algorithm
Proof:
In mathematical language, this problem is solved by finding integers x and y so that ax + by = 1. It is not hard to find that if gcd (a, B )! = 1, there must be no solution. On the contrary, if gcd (a, B) = 1, there must be an integer pair (x, y) Meeting ax + by = gcd (, b) You can use the Extended Euclidean algorithm to solve the problem.
Assume that we have obtained the Integer Solutions of B * xt + (a % B) yt = gcd (B, a % B) for xt, yt
According to Euclidean algorithm, gcd (B, a % B) = gcd (a, B)
Listen B * xt + (a % B) * yt = gcd (a, B) ①
Again, a % B = a-(a/B) * B ② Note: Because in C ++, the numbers of two int types are directly divided without special processing, the result is that the quotient of two numbers is rounded down to an integer.
∴ ② Into ① To simplify it: a * yt + B * (xt-(a/B) * yt) = gcd (a, B)
The Code is as follows:
Int extgcd (int a, int B, int & x, int & y) {int d = a; if (B! = 0) {d = extgcd (B, a % B, y, x); y-= (a/B) * x;} else {x = 1; y = 0;} return d ;}