Solving a Linear Diophantine Equation(see description for examples)

前端 未结 8 905
忘掉有多难
忘掉有多难 2020-12-16 20:27

Let me start off by clarifying that(before you guys dismiss me), this is not a homework problem and I\'m not a university student. :)

EDIT Thanks to

8条回答
  •  旧巷少年郎
    2020-12-16 20:42

    There are either no, or infinitely many solutions. It is often the case that you have an extra constraint that the solution must match. Is this the case in your problem?

    Let's start with the most simple situation where there are two unkowns a*x + b*y = c:

    The first step is using the Euclidean algorithm to find the GCD of a and b, let's call itd. As a bonus, the algorithm provides x' and y' such that a*x' + b*y' = d. If d doesn't divide c, then there is no solution. Otherwise, a solution is:

    x = x' * (c/d)
    y = y' * (c/d)
    

    The second step is to find all solutions. This means we must find all p and q such that a*p + b*q = 0. For if both (x,y) and (X, Y) are solutions, then

    a * (X-x) + b * (Y-y) = 0
    

    The answer to this is p = b/d and q = -a/d where d = GCD(a,b) and is already calculated in step 1. The general solution now is:

    x = x' * (c/d) + n * (b/d)
    y = y' * (c/d) - n * (a/d)
    

    where n is an integer.

    The first step is easy to extend to multiple variables. I am not sure about generalizing the second step. My first guess would be to find a solution for all pairs of coefficients and combine these solutions.

提交回复
热议问题