#include <bits/stdc++.h>
using namespace std;
template <class c>
struct rge {
  c b, e;
};
template <class c>
rge<c> range(c i, c j) {
  return rge<c>{i, j};
}
template <class c>
auto dud(c* x) -> decltype(cerr << *x, 0);
template <class c>
char dud(...);
struct debug {
  template <class c>
  debug& operator<<(const c&) {
    return *this;
  }
};
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    if (p % q != 0) {
      cout << p << "\n";
      continue;
    }
    vector<pair<long long, long long>> f;
    for (long long i = 2; i * i <= q; i++) {
      if (q % i) continue;
      long long cnt = 0;
      while (q % i == 0) {
        cnt++;
        q /= i;
      }
      f.push_back({i, cnt});
    }
    if (q > 1) f.push_back({q, 1});
    long long mx = 1;
    for (pair<long long, long long> x : f) {
      long long cp = p;
      while (cp % x.first == 0) cp /= x.first;
      for (long long i = 0; i < x.second - 1; i++) cp *= x.first;
      mx = max(mx, cp);
    }
    cout << mx << "\n";
  }
  return 0;
}
