#include <bits/stdc++.h>
using namespace std;
vector<pair<int64_t, int64_t> > factorize(long long n) {
  vector<pair<int64_t, int64_t> > v;
  int64_t ans = n, temp;
  int64_t coun = 0;
  while (!(n % 2)) {
    n >>= 1;
    coun++;
  }
  if (coun) {
    v.push_back(make_pair(2, coun));
  }
  for (long long i = 3; i <= sqrt(n); i += 2) {
    coun = 0;
    while (n % i == 0) {
      coun++;
      n = n / i;
    }
    if (coun) {
      v.push_back(make_pair(i, coun));
    }
  }
  if (n > 2) v.push_back(make_pair(n, 1));
  return v;
}
int32_t main() {
  int64_t i, j, p, q;
  int64_t t;
  cin >> t;
  while (t--) {
    cin >> p >> q;
    if (p % q != 0 || q > p)
      cout << p << '\n';
    else {
      int64_t ans = -1;
      vector<pair<int64_t, int64_t> > temp = factorize(q);
      for (i = 0; i < temp.size(); i++) {
        int64_t tempans = 0;
        int64_t t1 = p;
        while (t1 % temp[i].first == 0) {
          t1 /= temp[i].first;
        }
        int64_t zz = pow(temp[i].first, temp[i].second - 1);
        t1 *= zz;
        ans = max(ans, t1);
      }
      cout << ans << '\n';
    }
  }
  return 0;
}
