#include <bits/stdc++.h>
using namespace std;
inline long long isqrt(long long k) {
  long long r = sqrt(k) + 1;
  while (r * r > k) r--;
  return r;
}
inline long long icbrt(long long k) {
  long long r = cbrt(k) + 1;
  while (r * r * r > k) r--;
  return r;
}
inline long long mnz(long long& a, long long b) { return a = (a > b ? b : a); }
inline long long mxz(long long& a, long long b) { return a = (a < b ? b : a); }
inline string toString(long long n) {
  stringstream ss;
  ss << n;
  return ss.str();
}
double const eps = 1e-6;
long long const Base = 1e9 + 7, oo = 1e18 + 5, MAXN = 1e6;
long long A[MAXN + 5], B[MAXN + 5];
long long Solves() {
  long long n, m, k, cnt = 0, ans = 0, x, y, q, c, sum = 0, v, t;
  cin >> n >> m;
  if (n % m != 0) return cout << n << endl, 0;
  v = isqrt(m);
  c = m;
  vector<pair<long long, long long> > vec;
  for (long long i = 2; i <= v; i++) {
    if (c % i == 0) {
      t = 0;
      while (c % i == 0) {
        c /= i;
        t++;
      }
      vec.push_back(make_pair(i, t));
    }
  }
  if (c != 1) vec.push_back(make_pair(c, 1));
  c = oo;
  for (long long i = 0; i < vec.size(); i++) {
    v = n;
    t = 0;
    while (v % vec[i].first == 0) {
      v /= vec[i].first;
      t++;
    }
    v = 1;
    for (long long j = 1; j <= t - vec[i].second + 1; j++) v *= vec[i].first;
    mnz(c, v);
  }
  assert(n % c == 0);
  cout << n / c << endl;
  return 0;
}
int main() {
  if (fopen("locin.txt", "r")) freopen("locin.txt", "r", stdin);
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long test = 1;
  cin >> test;
  for (long long T = 1; T <= test; T++) {
    Solves();
  }
}
