#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  int T;
  cin >> T;
  while (T--) {
    long long p, q;
    cin >> p >> q;
    long long ans = -1;
    for (long long i = 1; i * i <= q; ++i) {
      long long pp = p;
      if (q % i == 0) {
        while (i != 1 and pp % q == 0 and pp % i == 0) {
          pp /= i;
        }
        long long ppp = p;
        while (ppp % q == 0 and ppp % (q / i) == 0) {
          ppp /= (q / i);
        }
        if (ppp % q != 0) ans = max(ans, ppp);
      }
      if (pp % q != 0) ans = max(ans, pp);
    }
    assert(ans != -1);
    cout << ans << "\n";
  }
  return 0;
}
