Decide in two steps.
At the first stage, calculate the description of the set {(x, y): x, y in Z and ax + by = K} using standard processing methods for the Diophantine equations . Let g = gcd (a, b); if g does not divide K, there are no solutions. Calculate g through the advanced Euclidean algorithm to solve ax '+ by' = g, and also calculate g; the first solution is (x ', y') * K / g. Other solutions are additively integer multiple (-b / g, a / g).
In step 2, calculate the description (x, y) of the solutions that can be achieved using different μ i options. Since K ≥ 0, we know that y ≥ 1 is a necessary condition. If n is a variable, then x ≥ 0 and y ≥ 1 is a necessary and sufficient condition (put μ 0 = y - 1 and μ x = 1, and all the rest μs to 0).
If n is a parameter, then everything is a bit sticky. Using the results of stage 1, we find a solution (x, y) with x ≥ 0 and y maximum (if there is no such solution, then K is impossible). For this solution, check if x / y ≤ n.
def egcd(A, B): """Returns a triple (gcd(A, B), s, t) such that s * A + t * B == gcd(A, B).""" a, b, s, t, u, v = A, B, 1, 0, 0, 1 while True: assert s * A + t * B == a assert u * A + v * B == b if not b: break q, r = divmod(a, b) a, b, s, t, u, v = b, r, u, v, s - q * u, t - q * v return a, s, t def solvable(K, a, b): g, s, t = egcd(a, b) q, r = divmod(K, g) if r: return False x, y = s * q, t * q assert a * x + b * y == K d = a // g q, r = divmod(y, d) if r <= 0: q -= 1 r += d assert 0 < r <= d x, y = x + q * (b // g), r assert a * x + b * y == K return x >= y