#include <bits/stdc++.h>
using namespace std;
void seive(vector<long long int>& v, long long int n) {
  v.push_back(n);
  for (int i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      v.push_back(i);
      if (i != n / i) v.push_back(n / i);
    }
  }
}
void run_case() {}
int main() {
  int t = 1;
  cin >> t;
  while (t--) {
    long long int p, q;
    cin >> p >> q;
    if (p % q) {
      cout << p << endl;
    } else {
      vector<long long int> v;
      seive(v, q);
      long long int ans = 1;
      for (auto i : v) {
        long long int tt = p;
        while (tt % i == 0) {
          tt = tt / i;
          if (tt % q != 0) {
            ans = max(ans, tt);
            break;
          }
        }
      }
      cout << ans << endl;
    }
  }
  return 0;
}
