#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  long long ans = 1;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    vector<long long> fac;
    vector<long long> val;
    long long pp = p;
    long long temp = q;
    if (q > p || p % q != 0) {
      cout << p << '\n';
      continue;
    }
    for (long long i = 2; i * i <= temp; i++) {
      if (temp % i == 0) {
        fac.push_back(i);
        long long kemp = 1;
        while (temp % i == 0) {
          kemp = kemp * i;
          temp = temp / i;
        }
        val.push_back(kemp);
      }
    }
    if (temp != 1) {
      fac.push_back(temp);
      val.push_back(temp);
    }
    for (int i = 0; i < fac.size(); i++) {
      while (p % fac[i] == 0) p = p / fac[i];
    }
    long long ans = 1;
    for (int i = 0; i < fac.size(); i++) {
      long long st = pp;
      while (st % fac[i] == 0) st = st / fac[i];
      st = (st * val[i]) / fac[i];
      ans = max(ans, st);
    }
    cout << ans << '\n';
  }
  return 0;
}
