30% 暴力枚举
另外20% 拓展欧几里得
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define LL long long
using namespace std;
LL L,R,m,s,p;
int T;
LL ex_gcd(LL a,LL b,LL &x,LL &y)
{
if(b==0)
{
x=1;
y=0;
return a;
}
LL ans=ex_gcd(b,a%b,x,y);
LL xx=x;
x=y;
y=xx-a/b*y;
return ans;
}
void work()
{
scanf("%lld%lld%lld%lld",&m,&s,&L,&R);
if(L>R||s%m==0||L>m) {printf("-1\n");return;}
if(L==R)
{
LL x,y;
p=ex_gcd(s,m,x,y);
if(R%p) {printf("-1\n");return;}
m=m/p;
printf("%lld\n",(x*L/p%m+m)%m);
return;
}
else
{
for(LL x=1;x;x++)
{
if(s*x%m<=R&&s*x%m>=L)
{
printf("%lld\n",x);
return;
}
}
}
}
int main()
{
freopen("she.in","r",stdin);
freopen("she.out","w",stdout);
scanf("%d",&T);
while(T--) work();
return 0;
}