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
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;
}