In the equation a + bx = c + dy
, all variables are integers. a
, b
, c
, and d
are known. How do I find integral solutions for x
and y
? If I'm thinking right, there will be an infinite number of solutions, separated by the lowest common multiple of b
and d
, but all I need is one solution, and I can calculate the rest. Here's an example:
a = 2
b = 3
c = 4
d = 5
a + bx: (2, 5, 8, 11, 14)
c + dy: (4, 9, 14, 19, 24)
a + bx intersects c + dy at 14, so:
x = 4
y = 2
Right now, I'm looping through integral values of x
until I find an integral value for y
(pseudocode):
function integral_solution(int a, int b, int c, int d) {
// a + bx == c + dy
// (a + bx - c) / d == y
// Some parameters may have no integral solution,
// for example if b == d and (a - c) % b != 0
// If we don't have a solution before x == d, there is none.
int x = 0;
while (x < d)
{
if ((a + bx - c) % d == 0)
{
return [x, (a + bx - c) / d];
}
x++;
}
return false;
}
I feel like there's a better way to do this. Is there any way to find x and y without a loop? I'm using C++, if that's of any importance.
Linear Diophantine equations take the form
ax + by = c
. Ifc
is the greatest common divisor ofa
andb
this meansa=z'c
andb=z''c
then this is Bézout's identity of the formwith
a=z'
andb=z''
and the equation has an infinite number of solutions. So instead of trial searching method you can check ifc
is the greatest common divisor (GCD) ofa
andb
(in your case this translates intobx - dy = c - a
)If indeed
a
andb
are multiples ofc
thenx
andy
can be computed using extended Euclidean algorithm which finds integersx
andy
(one of which is typically negative) that satisfy Bézout's identityand your answer is:
a = k*x
,b = k*y
,c - a = k * gcd(a,b)
for any integer k.(as a side note: this holds also for any other Euclidean domain, i.e. polynomial ring & every Euclidean domain is unique factorization domain). You can use Iterative Method to find these solutions:
Iterative method
By routine algebra of expanding and grouping like terms (refer to last section of wikipedia article mentioned before), the following algorithm for iterative method is obtained:
pseudocode:
So I have written example algorithm which calculates greatest common divisor using Euclidean Algorithm iterative method for non-negative
a
andb
(for negative - these extra steps are needed), it returns GCD and stores solutions forx
andy
in variables passed to it by reference:by passing to it an example from wikipedia for
a = 120
andb = 23
we obtain:r: 5,3,2,1,0,
q: 5,4,1,1,2,
x: 1,0,1,-4,5,-9,23,
y: 0,1,-5,21,-26,47,-120,
what is in accordance with the given table for this example: