#include <bits/stdc++.h>
inline long long min(const long long &a, const long long &b) {
  return a < b ? a : b;
}
inline long long max(const long long &a, const long long &b) {
  return a > b ? a : b;
}
long long p[100010], l, cnt[100010];
void get() {
  l = 0;
  long long a, b, i;
  scanf("%lld%lld", &a, &b);
  if (a < b || a % b) {
    printf("%lld\n", a);
    return;
  }
  for (i = 2; i * i <= b; i++) {
    if (b % i == 0) {
      p[++l] = i;
      cnt[l] = 0;
      while (b % i == 0) b /= i, cnt[l]++;
    }
  }
  if (b != 1) p[++l] = b, cnt[l] = 1;
  long long count, cp, ans = 0;
  for (i = 1; i <= l; i++) {
    count = 0, cp = a;
    while (cp % p[i] == 0) cp /= p[i], count++;
    count = min(count, cnt[i] - 1);
    if (count > 0)
      while (count--) cp *= p[i];
    ans = max(ans, cp);
  }
  printf("%lld\n", ans);
}
signed main() {
  long long T;
  scanf("%lld", &T);
  while (T--) get();
  return 0;
}
