#include <bits/stdc++.h>
using namespace std;
const int N = 1002;
class cmp {
 public:
  bool operator()(const pair<long long int, long long int> &a,
                  const pair<long long int, long long int> &b) {
    if (a.second != b.second) return a.second > b.second;
    return a.first > b.first;
  }
};
void solve() {
  long long int p, q;
  cin >> p >> q;
  if (p % q != 0) {
    cout << p << endl;
    return;
  }
  long long int ans = 0;
  vector<long long int> v;
  for (long long int i = 2; i <= sqrt(q); i++) {
    if (q % i == 0) {
      v.push_back(i);
      if (q / i != i) v.push_back(q / i);
    }
  }
  v.push_back(q);
  sort(v.begin(), v.end());
  for (long long int i = 0; i < v.size(); i++) {
    long long int x = p;
    long long int y = v[i];
    while (x % y == 0) {
      if (x % q != 0 || x < q) break;
      x = x / y;
    }
    ans = max(ans, x);
  }
  cout << ans << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
