#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int t;
  cin >> t;
  for (int z = 0; z < t; z++) {
    long long p, q;
    cin >> p >> q;
    if (p % q != 0) {
      cout << p << endl;
    } else {
      int Q = q;
      map<int, int> values;
      for (int j = 2; j * j <= q; j++) {
        while (q % j == 0) {
          values[j]++;
          q /= j;
        }
      }
      if (q != 1) {
        values[q]++;
      }
      long long res = 0;
      for (auto it : values) {
        long long cp = p;
        while (cp % Q == 0) {
          cp /= it.first;
        }
        res = max(res, cp);
      }
      cout << res << endl;
    }
  }
  return 0;
}
