#include <bits/stdc++.h>
using namespace std;
vector<long long> divi(long long n) {
  vector<long long> fcts;
  for (long long i = 1; i <= sqrt(n); i++) {
    if (n % i == 0) {
      if (n / i == i)
        fcts.push_back(i);
      else {
        fcts.push_back(i);
        fcts.push_back(n / i);
      }
    }
  }
  return fcts;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    if (p % q == 0) {
      vector<long long> divisors = divi(q);
      sort(divisors.begin(), divisors.end(), greater<long long>());
      long long ans = 1;
      for (auto i : divisors) {
        long long tem = p;
        while (tem % i == 0 && i > 1) {
          tem /= i;
          if (tem % q != 0) {
            ans = max(ans, tem);
            break;
          }
        }
      }
      cout << ans << "\n";
    } else {
      cout << p << "\n";
    }
  }
}
