#include <bits/stdc++.h>
using namespace std;
int mpow(int base, int exp);
void solve() {
  long long int p, q;
  cin >> p >> q;
  vector<pair<long long int, long long int> > pf;
  long long int tmp = q;
  for (long long int i = 2; i * i <= q; i++) {
    if (tmp % i == 0) {
      long long int cnt = 0;
      while (tmp % i == 0) {
        tmp /= i;
        cnt++;
      }
      pf.push_back({i, cnt});
    }
  }
  int orp = p;
  if (tmp != 1) pf.push_back({tmp, 1});
  vector<pair<long long int, long long int> > f;
  int x = q;
  for (int i = 2; i * i <= x; i++) {
    if (x % i == 0) {
      int cnt = 0;
      while (x % i == 0) {
        cnt++;
        x /= i;
      }
      f.push_back({i, cnt});
    }
  }
  if (x != 1) {
    f.push_back({x, 1});
  }
  long long int ans = p;
  long long int pp = p;
  for (auto it : pf) {
    long long int pri = it.first;
    long long int occ = it.second;
    long long int cnt = 0;
    while (pp % pri == 0) {
      pp /= pri, cnt++;
    }
    long long int mx = max(cnt - occ + 1, 0LL);
    long long int mul = 1;
    for (long long int i = 0; i < (mx); i++) mul *= pri;
    ans = min(ans, mul);
  }
  cout << p / ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}
int mpow(int base, int exp) {
  base %= 1000000007;
  int result = 1;
  while (exp > 0) {
    if (exp & 1) result = ((long long int)result * base) % 1000000007;
    base = ((long long int)base * base) % 1000000007;
    exp >>= 1;
  }
  return result;
}
