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