#include <bits/stdc++.h>
using namespace std;
long long p1 = 1000000, p2 = 0;
char buf[1000005], wb[1000005];
long long getint() {
  long long ret = 0, flag = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') flag = -1;
    c = getchar();
  }
  while (c <= '9' && c >= '0') {
    ret = (ret << 3) + (ret << 1) + c - '0';
    c = getchar();
  }
  return ret * flag;
}
void pc(char x) {
  if (p2 >= 1000000) fwrite(wb, 1, 1000000, stdout), p2 = 0;
  wb[p2++] = x;
}
void wrt(long long x) {
  if (x < 0) pc('-'), x = -x;
  long long c[24] = {0};
  if (!x) return pc('0'), void();
  while (x) c[++c[0]] = x % 10, x /= 10;
  while (c[0]) pc(c[c[0]--] + '0');
}
long long fac[1005], num[1005], ans;
int main() {
  int Ti = getint();
  while (Ti--) {
    ans = 0;
    long long p = getint(), q = getint(), x = 0;
    fac[0] = 0;
    if (p % q > 0)
      wrt(p), pc('\n');
    else {
      long long sq = sqrt(q);
      for (int i = 2; i <= sq; i++) {
        if (q % i == 0) {
          fac[++fac[0]] = i;
          num[fac[0]] = 0;
          while (q % i == 0) ++num[fac[0]], q /= i;
          sq = sqrt(q);
        }
      }
      if (q > 1) fac[++fac[0]] = q, num[fac[0]] = 1;
      for (int i = 1; i <= fac[0]; i++) {
        long long tp = p;
        while (tp % fac[i] == 0) tp /= fac[i];
        for (int j = 1; j < num[i]; j++) tp = tp * fac[i];
        ans = max(ans, tp);
      }
      wrt(ans), pc('\n');
    }
  }
  fwrite(wb, 1, p2, stdout);
  return 0;
}
