Source Code
#include "bits/stdc++.h"

using namespace std;
using int64 = int64_t;
using int128 = __int128_t;

const int ITERS = 1000;

void solve() {
  int64 n, a;
  cin >> n >> a;
  optional<pair<int128, int64>> ans;
  for (int i = 0; i < ITERS && n > 0; ++i) {
    int64 gcd = std::gcd(n, a);
    int128 res = a * n / gcd / gcd;
    if (!ans.has_value() || res >= ans.value().first) {
      ans = make_pair(res, n);
    }
    --n;
  }
  cout << ans.value().second << '\n';
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
Copy
LCM and GCD abdulrahman_aj
GNU G++17
2098 ms
328 KB
Time Limit Exceeded