Bezout’s identity
For non-zero integers
If
Example:
Extended Euclidean Algorithm
See divisibility for more details.
Implementation
/**
* Computes the values `x` and `y` for the equation
*
* ax + by = gcd(a, b)
*
* Given that `a` and `b` are positive integers
*
* @param {int} a
* @param {int} b
* @param {int} x
* @param {int} y
* @returns {int} gcd(a, b)
*/
int extended_euclidean(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
int x1, y1;
int gcd = extended_euclidean(b, a % b, x1, y1);
x = y1;
y = x1 - a / b * y1;
return gcd;
}
/**
* Alternative version using a vector of ints
* Computes the values x and y for the equation
*
* ax + by = gcd(a, b)
*
* @returns {vector<int>} A triplet with the values (gcd(a, b), x, y)
*/
vector<int> extended_euclidean(int a, int b) {
if (b == 0) {
// base case:
// b divides a so a(1) + b(0) = a
return vector<int> {a, 1, 0};
}
vector<int> t = extended_euclidean(b, a % b);
int gcd = t[0];
int x1 = t[1];
int y1 = t[2];
return vector<int> {gcd, y1, x1 - a / b * y1};
}
Applications
Diophantine equations
Equations with integer variables and coefficients are called Diophantine equations, the simplest non-trivial linear equation has the form
Where
Using the extended Euclidean algorithm it’s possible to find
multiplying it by
then one of the solutions is given by
where
we can find all of the solutions replacing
This process could be repeated for any number in the form
Where
/**
* Computes the integer values `x` and `y` for the equation
*
* ax + by = c
*
* if `c` is not divisible by `gcd(a, b)` then there isn't a valid solution,
* otherwise there's an infinite number of solutions, (`x`, `y`) form one pair
* of the set of possible solutions
*
* @param {int} a
* @param {int} b
* @param {int} c
* @param {int} x
* @param {int} y
* @returns {bool} True if the equation has solutions, false otherwise
*/
bool linear_diophantine_solution(int a, int b, int c, int &x, int &y) {
int gcd = extended_euclidean(abs(a), abs(b), x, y);
if (c % gcd != 0) {
// no solutions since c is not divisible by gcd(a, b)
return false;
}
x *= c / gcd;
y *= c / gcd;
if (a < 0) { x *= -1; }
if (b < 0) { y *= -1; }
return true;
}
Modular multiplicative inverse
See Modular Arithmetic for more info.
Linear congruence equations
A linear congruence is a congruence
By the definition of the congruence relation
Reordering the equation
Which is a linear diophantine equation discussed above, it’s solvable only if
https://brilliant.org/wiki/bezouts-identity/?subtopic=integers&chapter=greatest-common-divisor-lowest-common-divisor#proof http://www.ugrad.cs.ubc.ca/~cs490/Spring05/notes/nt1.pdf