#include <bits/stdc++.h>
using namespace std;
template <class T>
void aIn(T *a, int n) {
  for (int i = 0; i < n; i++) std::cin >> a[i];
}
template <class T>
void aOut(T *a, int n) {
  for (int i = 0; i < n; i++) std::cout << a[i] << " ";
  std::cout << endl;
}
template <class T>
void vOut(vector<T> &a) {
  for (T &x : a) std::cout << x << " ";
  std::cout << endl;
}
long long p, q;
long long gen(long long div) {
  long long mul = 1;
  long long tq = q;
  while (tq % div == 0) {
    tq /= div;
    mul *= div;
  }
  mul /= div;
  long long r = p;
  while (r % div == 0) r /= div;
  r = r * mul;
  return r;
}
void solv() {
  cin >> p >> q;
  if (p % q) {
    cout << p << endl;
    return;
  }
  long long ans = -1ll;
  bool prime = 1;
  for (long long x = 2; x * x <= q; x++) {
    if (q % x) continue;
    prime = 0;
    ans = max(ans, gen(x));
    ans = max(ans, gen(q / x));
  }
  if (prime) {
    ans = gen(q);
  }
  cout << ans << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  int t;
  cin >> t;
  while (t--) {
    solv();
  }
}
