#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void tomax(T &x, const T &y) {
  if (x < y) x = y;
}
template <class T>
inline void tomin(T &x, const T &y) {
  if (x > y) x = y;
}
inline long long read() {
  long long w = 0, f = 1;
  char c;
  while (!isdigit(c = getchar())) c == '-' && (f = -1);
  while (isdigit(c)) w = w * 10 + (c ^ 48), c = getchar();
  return w * f;
}
int T, b;
long long a;
int main() {
  int i;
  T = read();
  while (T--) {
    long long ans = 1;
    a = read(), b = read();
    if (a % b != 0) {
      printf("%lld\n", a);
      continue;
    }
    for (i = 2; i * i <= b; i++)
      if (b % i == 0) {
        long long x = a;
        while ((x / i) % b == 0) x /= i;
        x /= i;
        while (b % i == 0) b /= i;
        ans = max(ans, x);
      }
    if (b > 1) {
      long long x = a;
      while ((x / b) % b == 0) x /= b;
      x /= b;
      ans = max(ans, x);
    }
    printf("%lld\n", ans);
  }
  return 0;
}
