#include <bits/stdc++.h>
using namespace std;
const int maxn = 105;
int cnt(long long n, long long p) {
  int res = 0;
  while (n != 0 && n % p == 0) {
    res++;
    n /= p;
  }
  return res;
}
long long pow(long long a, long long b) {
  long long res = 1;
  for (int i = 1; i <= b; i++) res *= a;
  return res;
}
long long max(long long a, long long b) { return a > b ? a : b; }
int main() {
  long long n, t, p, q;
  map<long long, long long> mp;
  cin >> t;
  while (t--) {
    cin >> p >> q;
    if (p % q != 0) {
      printf("%lld\n", p);
      continue;
    } else {
      long long res = 0;
      for (int i = 2; i <= sqrt(q); i++) {
        if (q % i == 0) {
          int cntp = cnt(p, i);
          int cntq = cnt(q, i);
          res = max(res, p / pow(i, cntp - cntq + 1));
          cntp = cnt(p, q / i);
          cntq = cnt(q, q / i);
          res = max(res, p / pow(q / i, cntp - cntq + 1));
        }
      }
      if (res == 0) {
        int cntp = cnt(p, q);
        int cntq = cnt(q, q);
        res = max(res, p / pow(q, cntp - cntq + 1));
      }
      printf("%lld\n", res);
    }
  }
  return 0;
}
