#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
void solve() {
  long long p, q;
  cin >> p >> q;
  long long g = p;
  long long t = q;
  map<long long, long long> f, l;
  for (long long i = 2; i * i <= t; i++) {
    if (t % i == 0) {
      while (g % i == 0) {
        g /= i;
        f[i]++;
      }
      while (t % i == 0) {
        t /= i;
        l[i]++;
      }
    }
  }
  if (t != 1) {
    while (g % t == 0) {
      g /= t;
      f[t]++;
    }
    l[t]++;
    t = 1;
  }
  long long ans = g;
  for (auto x : l) {
    long long u = p;
    for (int i = 0; i < max(0ll, f[x.first] - x.second + 1); i++) u /= x.first;
    ans = max(ans, u);
  }
  cout << ans;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int q = 1;
  cin >> q;
  for (; q > 0; q--) {
    solve();
    cout << endl;
  }
}
