#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    long long int p, q;
    cin >> p >> q;
    if (p % q) {
      cout << p << "\n";
    } else {
      vector<pair<long long int, long long int> > candidates;
      for (int i = 2; i * i <= q; i++) {
        if (q % i == 0) {
          long long int count = 0;
          while (q % i == 0) {
            q /= i;
            count++;
          }
          candidates.push_back(make_pair(i, count));
        }
      }
      if (q > 1) {
        candidates.push_back(make_pair(q, 1));
      }
      long long int result = 1;
      for (int i = 0; i < candidates.size(); i++) {
        long long int x = candidates[i].first, count = candidates[i].second,
                      fake_p = p;
        while (fake_p % x == 0) {
          fake_p /= x;
        }
        for (int i = 1; i < count; i++) {
          fake_p *= x;
        }
        result = max(result, fake_p);
      }
      cout << result << "\n";
    }
  }
  return 0;
}
