#include <bits/stdc++.h>
using namespace std;
int t, i;
int c[32650];
void ciu();
unsigned long long int p, q;
unsigned long long int minim = 0xffffffffffffffff;
vector<unsigned long long int> v;
int main() {
  cin >> t;
  ciu();
  while (t--) {
    minim = 0xffffffffffffffff;
    cin >> p >> q;
    if (p % q != 0)
      cout << p << '\n';
    else {
      for (i = 0; i < v.size() && v[i] * v[i] <= q; i++)
        if (q % v[i] == 0) {
          unsigned long long int exp = 0, rez = 1;
          while (q % v[i] == 0) {
            q /= v[i];
            exp++;
            rez *= v[i];
          }
          if (rez != 1) {
            unsigned long long int expx = 0, rezx = 1;
            unsigned long long int cp = p;
            cp /= rez;
            while (cp % v[i] == 0) {
              cp /= v[i];
              expx++;
              rezx *= v[i];
            }
            rezx *= v[i];
            if (rezx < minim) minim = rezx;
          }
        }
      if (q != 1) {
        unsigned long long int expq = 0, rezq = 1;
        unsigned long long int cp = p;
        cp /= q;
        while (cp % q == 0) {
          cp /= q;
          expq++;
          rezq *= q;
        }
        rezq *= q;
        if (rezq < minim) minim = rezq;
      }
      cout << p / minim << '\n';
    }
  }
  return 0;
}
void ciu() {
  int i, j;
  for (i = 2; i * i < 32650; i++)
    if (!c[i])
      for (j = i * i; j < 32650; j += i) c[j] = 1;
  for (i = 2; i < 32650; i++)
    if (!c[i]) v.push_back(i);
}
