How to solve Linear Diophantine equations in programming?

前端 未结 2 1653
深忆病人
深忆病人 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: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;
    }
    

提交回复
热议问题