I'm trying to write an algorithm to determine whether a linear equation, specifically in the form of ax + by = c, has positive integer solutions for given a,b,c. It needs to be efficient since the numbers a, b, and c can be in range 0<=a,b,c<=10^16. How would I approach this problem?
Since it's a diophantine equation in question, I tried to check if the GCD of a and b divides c, but this way I can't differentiate between positive, negative, or zero solutions.
Algorithm to determine non-negative-values solution existance for linear diophantine equation
I found a solution here, but I didn't quite understand it. Maybe someone can simplify it for me? Since this one is pretty general and I'm only interested in equations with 2 variables.
Existence of integer solutions
Bezout's identity tells you indeed that with
gcd(a,b)
the greatest common divisor of a and b:So there you go. If
c
is dividable bygcd(a,b)
, you have solutions.Finding positive solutions
From any pair of solutions, we can get all the other ones. Thus we can see if they can be positive. Still from the same identity, we get:
And now we're done. All you have to do is :
gcd(a,b)
and(x0,y0)
such thata * x0 + b * y0 = gcd(a,b)
gcd(a,b)
dividesc
.x0
andy0
byc / gcd(a,b)
to get solutions for your equation.x0
andy0
both have the same sign, you're done.x0
andy0
have different signs, choose the smallest (in absolute value)k
to change the sign of the negative integer.x0
is negative, then takek = floor(d * x0 / b)
(rounding to -infinity)and if is
y0
is negative, takek = ceil(-d * y0 / a)
(x1,y1) = (x0 - k * b / d , y0 + k * a / d)
x1
andy1
are both positive, you just found two positive integer solutions.Note that it is related to the question you linked, but the number of variables is different. This is solved because you only have two variables.