思路:
水题;
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>using namespace std;#define ll long longinline void in(ll &now)
{
char Cget=getchar();now=;
while(Cget>''||Cget<'') Cget=getchar();
while(Cget>=''&&Cget<='')
{
now=now*+Cget-'';
Cget=getchar();
}
}ll gcd(ll a,ll b)
{
return b?gcd(b,a%b):a;
}int main()
{
ll t,x,y,p,q;
in(t);
for(;t--;)
{
in(x),in(y),in(p),in(q);
p/=gcd(p,q),q/=gcd(p,q);
if(q==p)
{
if(x!=y)
{
printf("-1\n");
continue;
}
}
if(p==)
{
if(x!=)
{
printf("-1\n");
continue;
}
}
ll pos=(q-y%q)%q;
double ki=(double)p/(double)q,li,ri;
ll l=,r=,ans;
while(l<=r)
{
int mid=l+r>>;
li=(double)x/(double)(y+pos+(mid*q));
ri=(double)(x+pos+mid*q)/(double)(y+pos+mid*q);
if(ki>=li&&ki<=ri) ans=mid,r=mid-;
else l=mid+;
}
printf("%lld\n",pos+ans*q);
// cout<<pos+ans*q;
// putchar('\n');
}
return ;
}