#include <bits/stdc++.h>
using namespace std;
signed main() {
  long long t;
  cin >> t;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    if (p % q != 0) {
      cout << p << endl;
      continue;
    }
    long long w = sqrt(q);
    long long ma = 1;
    long long h;
    for (long long i = 2; i <= w; i++) {
      if (q % i == 0) {
        h = p / i;
        while (h % q == 0) {
          h = h / i;
        }
        ma = max(ma, h);
        long long u = q / i;
        h = p / u;
        while (h % q == 0) {
          h = h / u;
        }
        ma = max(ma, h);
      }
    }
    h = p;
    while (h % q == 0) {
      h = h / q;
    }
    ma = max(h, ma);
    cout << ma << endl;
  }
}
