How to solve Linear Diophantine equations in programming?

前端 未结 2 1657
深忆病人
深忆病人 2021-02-06 18:41

I have read about Linear Diophantine equations such as ax+by=c are called diophantine equations and give an integer solution only if gcd(a,b) divides c

相关标签:
2条回答
  • 2021-02-06 19:02

    Solving Linear Diophantine equations

    ax + by = c and gcd(a, b) divides c.

    1. Divide a, b and c by gcd(a,b).
    2. Now gcd(a,b) == 1
    3. Find solution to aU + bV = 1 using Extended Euclidean algorithm
    4. Multiply equation by c. Now you have a(Uc) + b (Vc) = c
    5. You found solution x = U*c and y = V * c
    0 讨论(0)
  • 2021-02-06 19:07

    The problem is that the input values are 64-bit (up to 10^18) so the LCM can be up to 128 bits large, therefore l can overflow. Since k is 64-bit, an overflowing l indicates k = 0 (so answer is 1). You need to check this case.

    For instance:

    unsigned long long l=g1/g; // cannot overflow
    unsigned long long res;
    if ((l * g2) / g2 != l)
    {
        // overflow case - l*g2 is very large, so k/(l*g2) is 0
        res = 0;
    }
    else
    {
        l *= g2;
        res = k / l;
    }
    
    0 讨论(0)
提交回复
热议问题