#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vl = vector<long long>;
using vvi = vector<vector<int>>;
using vvl = vector<vector<long>>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using u32 = uint32_t;
using u64 = uint64_t;
template <typename T>
void re(T &x);
template <typename T>
void re(vector<T> &v);
template <typename T, typename... Q>
void re(T &x, Q &...y);
template <typename T>
void re(T &x) {
  cin >> x;
}
template <typename T>
void re(vector<T> &v) {
  for (auto &x : v) re(x);
}
template <typename T, typename... Q>
void re(T &x, Q &...y) {
  re(x);
  re(y...);
}
namespace number_theory {
template <typename T>
std::vector<std::pair<T, int>> factor(T x) {
  if (x <= 1) return {};
  std::vector<std::pair<T, int>> pr;
  for (T i = 2; i * i <= x; ++i) {
    if (x % i == 0) {
      int n = 0;
      while (x % i == 0) x /= i, ++n;
      pr.push_back({i, n});
    }
  }
  if (x > 1) pr.push_back({x, 1});
  return pr;
}
ll phi(ll x) {
  for (auto &i : factor(x)) x -= x / i.first;
  return x;
}
}  // namespace number_theory
ll solve(ll p, ll q) {
  if (p % q != 0) {
    return p;
  } else {
    ll ans = 1;
    for (auto &f : number_theory::factor(q)) {
      ll P = p;
      for (P = p; P % q == 0;) P /= f.first;
      ans = max(ans, P);
    }
    return ans;
  }
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    ll p, q;
    cin >> p >> q;
    cout << solve(p, q) << '\n';
  }
}
