#include <bits/stdc++.h>
using namespace std;
const int64_t N = 5e2 + 5, lg = 15;
void solve() {
  int64_t n, m, p, ans = 1;
  cin >> n >> m;
  if (n % m) {
    cout << n << endl;
    return;
  }
  vector<int64_t> z;
  p = m;
  for (int64_t i = 2; i * i <= p; i++) {
    if (p % i == 0) {
      z.push_back(i);
      while (p % i == 0) {
        p /= i;
      }
    }
  }
  if (p - 1) {
    z.push_back(p);
  }
  for (int64_t it : z) {
    int64_t k = n;
    while (k % it == 0) {
      k /= it;
      if (k % m) {
        ans = max(ans, k);
      }
    }
  }
  cout << ans << endl;
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int64_t t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
}
