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

后端 未结 1 1623
猫巷女王i
猫巷女王i 2021-01-24 09:51

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

1条回答
  •  伪装坚强ぢ
    2021-01-24 10:33

    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 讨论(0)
提交回复
热议问题