扩展欧几里德算法
列方程dt-ln = y-x
求基础解,在求最小t解
代码如下:
#include <cstdio>
void gcd(long long a, long long b,long long &d,long long &x, long long &y)
{
if(b==0) {x = 1; y = 0; d = a;}
else {gcd(b,a%b,d,y,x); y-=(a/b)*x;}
}
int main ()
{
long long n, d, x, y;
int cas;
scanf("%d",&cas);
while(cas--)
{
scanf("%lld%lld%lld%lld",&n,&d,&x,&y);
long long a = d, b = n, c = y-x, dg;
gcd(a,b,dg,x,y);
if(c%dg) printf("Impossible\n");
else
{
long long g = c/dg, k = b/dg;
x *= g;
printf("%lld\n",(x%k+k)%k);
}
}
return 0;
}