#include <bits/stdc++.h>
using namespace std;
long long p, q, x;
map<long long, int> rtq;
void div(map<long long, int>& mp, long long v) {
  for (long long i = 2; i <= sqrt(v); i++) {
    int cnt = 0;
    while (v % i == 0) {
      cnt++;
      v /= i;
    }
    if (cnt != 0) mp[i] = cnt;
  }
  if (v > 1) {
    mp[v] = 1;
  }
}
long long calc(long long v, long long x) {
  long long ret = 1;
  for (long long i = 1; i <= x; i++) ret *= v;
  return ret;
}
long long solve(long long val, map<long long, int>& rt) {
  long long ret = -1;
  for (auto item : rt) {
    long long v = item.first;
    long long val_now = val;
    int cnt = 0;
    while (val_now % v == 0) {
      val_now /= v;
      ++cnt;
    }
    long long div_now = calc(v, cnt - item.second + 1);
    ret = max(ret, val / div_now);
  }
  return ret;
}
int w33ha() {
  rtq.clear();
  scanf("%lld%lld", &p, &q);
  if (p % q != 0) return printf("%lld\n", p);
  div(rtq, q);
  printf("%lld\n", solve(p, rtq));
  return 0;
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) w33ha();
  return 0;
}
