#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long p, q;
  cin >> p >> q;
  if (p % q != 0) {
    cout << p << endl;
    return;
  }
  map<long long, long long> mymap;
  while (q % 2 == 0) q = q >> 1, mymap[2]++;
  long long ttt = sqrt(q);
  for (long long i = 3; i <= ttt; i += 2) {
    while (q % i == 0) q /= i, mymap[i]++;
    if (q == 1) break;
  }
  if (q > 1) mymap[q]++;
  long long divideby = 1;
  for (auto i : mymap) {
    long long temp = p;
    long long cnt = 0;
    while (temp % i.first == 0) temp /= i.first, cnt++;
    long long pp = pow(i.first, cnt - i.second + 1);
    if (divideby == 1 || pp < divideby) divideby = pp;
  }
  cout << p / divideby << endl;
}
int main() {
  int t;
  cin >> t;
  while (t--) solve();
}
