How to solve Linear Diophantine equations in programming?

倾然丶 夕夏残阳落幕 提交于 2019-12-03 04:58:08

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

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