#include <bits/stdc++.h>
using namespace std;
long long unsigned t, p, q, k, cnt, cn2, ans, pp, qq, m, qt, tt, pr[100050];
bool np[100050];
inline long long unsigned gcd(long long unsigned m, long long unsigned n) {
  while (n != 0) {
    tt = m % n;
    m = n;
    n = tt;
  }
  return m;
}
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  for (register long long unsigned i = 2; i <= 100000; ++i) {
    if (!np[i]) pr[++k] = i;
    for (register long long unsigned j = 1; j <= k && i * pr[j] <= 100000;
         ++j) {
      np[i * pr[j]] = 1;
      if (!(i % pr[j])) break;
    }
  }
  cin >> t;
  for (register long long unsigned ti = 1; ti <= t; ++ti) {
    cin >> p >> q;
    if (gcd(p, q) == 1 || p % q != 0) {
      cout << p << endl;
      continue;
    }
    ans = 0;
    qt = q;
    for (register long long unsigned i = 1; i <= k; ++i)
      if (q % pr[i] == 0 && p % pr[i] == 0) {
        pp = p;
        while (pp % q == 0 && pp % pr[i] == 0) {
          pp /= pr[i];
          qt /= pr[i];
        }
        if ((pp % q) && pp > ans) ans = pp;
      }
    if (qt > 1)
      if (q % qt == 0 && p % qt == 0) {
        pp = p;
        while (pp % q == 0 && pp % qt == 0) {
          pp /= qt;
        }
        if ((pp % q) && pp > ans) ans = pp;
      }
    cout << ans << endl;
  }
  return 0;
}
