fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3.  
  4.  
  5. using namespace std;
  6. #define ll long long
  7. ll x,y,p,q;
  8. ll f(ll a)
  9. {
  10.  
  11. ll num=(a*p-x);
  12. ll denum=(a*q-y);
  13. if(denum<0||num<0)
  14. {
  15. return 0;
  16. }
  17. if(denum>=num)
  18. {
  19. return 1;
  20. }
  21. else
  22. {
  23. return 0;
  24. }
  25. }
  26. int main()
  27. {
  28. //cout << "Hello world!" << endl;
  29. ll i,j ,k,t;
  30. cin>>t;
  31. while(t--)
  32. {
  33. cin>>x>>y>>p>>q;
  34.  
  35. if((double)x/y==(double)p/q)
  36. {
  37. cout<<"0\n";
  38. continue;
  39. }
  40. if(p>=q&&x!=y)
  41. {
  42. cout<<"-1\n";
  43. continue;
  44. }
  45. ll lo=(x/p),hi=10e9;
  46. ll mid;
  47. ll last=-1;
  48. while(lo<hi)
  49. {
  50.  
  51. mid=lo+(hi-lo)/2;
  52.  
  53. if(f(mid))
  54. {
  55. last=mid;
  56. hi=mid;
  57. }
  58. else
  59. {
  60. lo=mid+1;
  61. }
  62. }
  63. ll ans=(q*last-y);
  64. cout<<ans<<"\n";
  65. }
  66.  
  67. return 0;
  68. }
  69.  
Runtime error #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty