#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  long long int t = 1;
  cin >> t;
  while (t--) {
    long long int p, q, x;
    cin >> p >> q;
    long long int b = 0;
    set<long long int> pf;
    long long int cq = q;
    for (long long int i = 2; i * i <= cq; i++) {
      while (cq % i == 0) {
        pf.insert(i);
        cq /= i;
      }
    }
    if (cq > 1) pf.insert(cq);
    for (long long int i : pf) {
      long long int cp = p;
      while (cp % q == 0) cp /= i;
      b = max(b, cp);
    }
    cout << b << endl;
  }
}
