#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T>
bool chmax(T &val, T nv) {
  return val < nv ? (val = nv, true) : false;
}
template <class T>
bool chmin(T &val, T nv) {
  return val > nv ? (val = nv, true) : false;
}
const int MAX_N = 300010;
vector<pair<ll, ll>> prifac(ll val) {
  vector<pair<ll, ll>> fac;
  for (ll i = 2; i * i <= val; ++i) {
    if (val % i == 0) {
      fac.emplace_back(i, 1);
      while (val % i == 0) {
        val /= i;
        fac.back().second *= i;
      }
    }
  }
  if (val != 1) fac.emplace_back(val, val);
  return fac;
}
ll solve() {
  ll p, q;
  cin >> p >> q;
  if (p < q) return p;
  ll res = 1;
  vector<pair<ll, ll>> fac = prifac(q);
  for (auto [v, all] : fac) {
    ll cg = p;
    while (cg % all == 0) cg /= v;
    res = max(res, cg);
  }
  return res;
}
signed main() {
  ios_base::sync_with_stdio(0), cin.tie(0);
  int T;
  cin >> T;
  while (T--) cout << solve() << '\n';
}
