#include <bits/stdc++.h>
using namespace std;
struct PrimeFactorization {
  using number_type = long long;
  using exponent_type = int;

 private:
  map<number_type, exponent_type> factors_;
  number_type n;

 public:
  PrimeFactorization(number_type nn) : n(nn) {
    for (number_type i = 2; i * i <= nn; ++i)
      while (nn % i == 0) ++factors_[i], nn /= i;
    if (nn != 1) ++factors_[nn];
  }
  const map<number_type, exponent_type>& factors() const { return factors_; }
};
template <typename T, typename U>
T& upd_max(T& a, const U& b) {
  return a = max(a, static_cast<T>(b));
}
void solve() {
  using ll = long long;
  ll p, q;
  cin >> p >> q;
  if (p % q)
    cout << p << '\n';
  else {
    PrimeFactorization fq(q);
    ll ans = 1;
    for (const auto& [n, ignore] : fq.factors()) {
      ll t = p;
      while (t % q == 0) t /= n;
      upd_max(ans, t);
    }
    cout << ans << '\n';
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) solve();
  return 0;
}
