AhmedAshraff

Untitled

Jul 19th, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. typedef long long ll;
  5. #define sz(s) (int)(s).size()
  6. #define all(s) s.begin(), s.end()
  7.  
  8. void Speed()
  9. {
  10.     ios_base::sync_with_stdio(false);
  11.     cin.tie(NULL);
  12.     // #ifndef ONLINE_JUDGE
  13.     //     freopen("input.txt", "r", stdin);
  14.     //     freopen("output.txt", "w", stdout);
  15.     // #endif
  16. }
  17.  
  18. int power(int a,  int n , int m){
  19.     if(!n)
  20.         return 1 % m;
  21.     int res = power(a , n / 2,m);
  22.     res = 1LL * res * res % m;
  23.     if(n & 1)
  24.         res = 1LL * res * a % m;
  25.     return res;
  26. }
  27.  
  28. int get_k(int a , int b , int d){
  29.     if(b == 1){
  30.         if(a % d == 0)
  31.             return 0;
  32.         return -1;
  33.     }
  34.     d /= __gcd(a , d);
  35.     if(d == 1)
  36.         return 0;
  37.     for(int k = 1; k <= 50; k++){
  38.         d /= __gcd(d , b);
  39.         if(d == 1)
  40.             return k;
  41.     }
  42.     return -1;
  43. }
  44.  
  45. int eGCD(int a, int b, int &x, int &y) {
  46.  x = 1;
  47.  y = 0;
  48.  int nx = 0, ny = 1;
  49.  int t, r;
  50.  while (b) {
  51.   r = a / b;
  52.   t = a - r * b;
  53.   a = b;
  54.   b = t;
  55.   t = x - r * nx;
  56.   x = nx;
  57.   nx = t;
  58.   t = y - r * ny;
  59.   y = ny;
  60.   ny = t;
  61.  }
  62.  return a;
  63. }
  64.  
  65. int modInv(int a, int m) {
  66.  int mi, r;
  67.  eGCD(a, m, mi, r);
  68.  return (mi + m) % m;
  69. }
  70.  
  71. void solve(){      
  72.     ll a , b , d;
  73.     cin >> a >> b >> d;
  74.  
  75.     int rem = (-a%d + d) % d;
  76.  
  77.     int g = __gcd(b,d);
  78.     if(rem % g){
  79.         cout << "-1\n";
  80.         return;
  81.     }
  82.  
  83.     int k = get_k(a,b,d);
  84.     if(k == -1){
  85.         cout << k << "\n";
  86.         return;
  87.     }
  88.  
  89.  
  90.     int _b = b / g , _d = d / g , _rem = rem / g;
  91.  
  92.     int inv = modInv(_b,_d);
  93.  
  94.     int kth = 1LL * inv * _rem % _d;
  95.     while(kth < k)
  96.         kth += _d;
  97.  
  98.     // cout << (kth * _b) % _d << " " << _rem  << " ~\n";
  99.     int ans = max(k,kth);
  100.  
  101.     cout << ans << "\n";
  102.  
  103. }
  104.  
  105. int main()
  106. {
  107.     Speed();
  108.     int tc = 1;
  109.     cin >> tc;
  110.     while (tc--)
  111.     {
  112.         solve();
  113.     }
  114.     return 0;
  115. }
Advertisement
Add Comment
Please, Sign In to add comment