#include <bits/stdc++.h>
using namespace std;
long long m = 1000000007;
long long fact(long long n);
int modInverse(int a, int m) {
  int m0 = m;
  int y = 0, x = 1;
  if (m == 1) return 0;
  while (a > 1) {
    int q = a / m;
    int t = m;
    m = a % m, a = t;
    t = y;
    y = x - q * y;
    x = t;
  }
  if (x < 0) x += m0;
  return x;
}
long long fact(long long n) {
  long long res = 1;
  for (long long i = 2; i <= n; i++) res = (res % m * i % m) % m;
  return res;
}
int main() {
  long long t;
  cin >> t;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    long long s = 1;
    if (p < q) {
      cout << p << endl;
      continue;
    }
    if (p % q) {
      cout << p << endl;
      continue;
    }
    vector<long long> v;
    v.push_back(q);
    for (long long i = 2; i * i <= q; i++) {
      if (q % i == 0) {
        v.push_back(i);
        if (i != q / i) v.push_back(q / i);
      }
    }
    for (long long i = 0; i < v.size(); i++) {
      long long x = p;
      while (x % v[i] == 0) {
        x = x / v[i];
        if (x % q != 0) {
          s = max(s, x);
          break;
        }
      }
    }
    cout << s << endl;
  }
  return 0;
}
