#include <bits/stdc++.h>
using namespace std;
int ioo = INT_MAX;
long long Loo = LONG_LONG_MAX;
long long power(long long fa, long long n) {
  long long k = 1;
  while (n) {
    if (n % 2) k = (k * fa) % (long long)(1000000000 + 7);
    fa = (fa * fa) % (long long)(1000000000 + 7);
    n /= 2;
  }
  return k;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr), cout.tie(nullptr);
  int t;
  cin >> t;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    if (p % q)
      cout << p << endl;
    else {
      long long ans = 1;
      for (long long i = 2; i * i <= q; i++) {
        if (q % i == 0) {
          long long tp = p;
          while (tp % i == 0) tp /= i;
          long long k = 1;
          while (q % i == 0) q /= i, k *= i;
          k /= i;
          ans = max(ans, tp * k);
        }
      }
      if (q != 1) {
        while (p % q == 0) p /= q;
        ans = max(ans, p);
      }
      cout << ans << endl;
    }
  }
  return 0;
}
