Codeforces Round #412 C - Success Rate
算出最小倍数就可以了
p要大于等于y
q要大于等于x
对于x增加 y也随增加
(y-x)*i<=(p-q)
#include <stdio.h>
#include <bits/stdc++.h>
#define read(); freopen("input.txt","r",stdin);
using namespace std;
typedef long long ll;
int t;
int gcd(int n,int m){
if(n%m==0) return m;
return gcd(m,n%m);
}
int main()
{
cin>>t;
while(t--){
ll x,y,p,q;
cin>>x>>y>>p>>q;
if(p/q==1){
if(x/y==1)
cout<<0<<endl;
else cout<<-1<<endl;
continue;
}
if(p==0){
if(x==0)
cout<<0<<endl;
else cout<<-1<<endl;
continue;
}
int k=gcd(p,q);
p/=k;q/=k;
ll ans=0;
ll maxn= (y-x)/(q-p)+((y-x)%(q-p)?1:0);
maxn=max(maxn,y/q+(y%q?1:0));
maxn=max(maxn,x/p+(x%p?1:0));
ans=q*maxn-y;
cout<<ans<<endl;
}
return 0;
}