#include <bits/stdc++.h>
using namespace std;
void gcd(unsigned long long n,
         unordered_map<unsigned long long, unsigned long long> &hash) {
  while (n % 2 == 0) {
    hash[2]++;
    n = n / 2;
  }
  for (unsigned long long i = 3; i <= sqrt(n); i = i + 2) {
    while (n % i == 0) {
      hash[i]++;
      n = n / i;
    }
  }
  if (n > 2) hash[n]++;
  return;
}
int32_t main() {
  unsigned long long t;
  cin >> t;
  for (unsigned long long count = 1; count <= t; count++) {
    unsigned long long p, q;
    cin >> p >> q;
    if (q > p)
      cout << p << endl;
    else {
      if (p % q == 0) {
        unordered_map<unsigned long long, unsigned long long> hash;
        gcd(q, hash);
        unsigned long long mi = 0;
        for (auto it : hash) {
          unsigned long long factor = it.first;
          unsigned long long count = it.second;
          unsigned long long curr = 1;
          unsigned long long temp = p;
          while (temp % q == 0) {
            temp /= factor;
            curr *= factor;
          }
          mi = max(mi, temp);
        }
        cout << mi << endl;
      } else
        cout << p << endl;
    }
  }
  return 0;
}
