What's algorithm used to solve Linear Diophantine equation: ax + by = c

帅比萌擦擦* 提交于 2019-12-04 05:32:38

问题


I'm looking for integers solution here. I know it has infinitely many solution derived from the first pair solution and gcd(a,b)|c. However, how could we find the first pair of solution? Is there any algorithm to solve this problem?

Thanks,
Chan


回答1:


Note that there isn't always a solution. In fact, there's only a solution if c is a multiple of gcd(a, b).

That said, you can use the extended euclidean algorithm for this.

Here's a C++ function that implements it, assuming c = gcd(a, b). I prefer to use the recursive algorithm:

function extended_gcd(a, b)
    if a mod b = 0
        return {0, 1}
    else
        {x, y} := extended_gcd(b, a mod b)
        return {y, x-(y*(a div b))}

int ExtendedGcd(int a, int b, int &x, int &y)
{
    if (a % b == 0)
    {
        x = 0;
        y = 1;
        return b;
    }

    int newx, newy;
    int ret = ExtendedGcd(b, a % b, newx, newy);

    x = newy;
    y = newx - newy * (a / b);
    return ret;
}

Now if you have c = k*gcd(a, b) with k > 0, the equation becomes:

ax + by = k*gcd(a, b) (1)
(a / k)x + (b / k)y = gcd(a, b) (2)

So just find your solution for (2), or alternatively find the solution for (1) and multiply x and y by k.



来源:https://stackoverflow.com/questions/4917003/whats-algorithm-used-to-solve-linear-diophantine-equation-ax-by-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!