开发者

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

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?

开发者_StackOverflow社区

Thanks,

Chan


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜