#include <bits/stdc++.h>
using namespace std;
int t;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  cin >> t;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    if (p % q != 0) {
      cout << p << endl;
      continue;
    }
    vector<long long> fac_q;
    for (long long val = 2; val * val <= q; ++val) {
      if (q % val == 0) {
        fac_q.push_back(val);
        fac_q.push_back(q / val);
      }
    }
    fac_q.push_back(q);
    long long ans = 1;
    for (long long &f : fac_q) {
      long long x = p;
      while (x % q == 0) {
        x /= f;
      }
      ans = max(ans, x);
    }
    cout << ans << endl;
  }
  cerr << "Time : " << (double)clock() / (double)CLOCKS_PER_SEC << "s\n";
  return 0;
}
