#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > primeFactorise(long long n) {
  vector<pair<int, int> > primeFactors;
  for (long long i = 2; i * i <= n; i++) {
    long long power = 0;
    while (n % i == 0) {
      power++;
      n /= i;
    }
    if (power) primeFactors.push_back({i, power});
  }
  if (n > 1) primeFactors.push_back({n, 1});
  return primeFactors;
}
long long exp(long long b, long long e) {
  long long ans = 1;
  while (e) {
    if (e & 1) ans *= b;
    b = b * b;
    e >>= 1;
  }
  return ans;
}
void solve() {
  long long p, q;
  cin >> p >> q;
  if (p % q != 0) {
    printf("%lld\n", p);
    return;
  }
  vector<pair<int, int> > pf = primeFactorise(q);
  long long best = 1;
  for (int i = 0; i < (int)pf.size(); i++) {
    int power = 0;
    long long n = p;
    while (n % pf[i].first == 0) {
      n /= pf[i].first;
      power++;
    }
    long long factor = exp(pf[i].first, power - pf[i].second + 1);
    best = max(best, p / factor);
  }
  printf("%lld\n", best);
}
int main() {
  int t;
  cin >> t;
  for (int i = 0; i < t; i++) solve();
}
