#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
const int inf = 0x3f3f3f3f;
const long long inF = 0x3f3f3f3f3f3f3f3f;
const long long mod = 1e9 + 7;
const double eps = 1e-8;
long long prime[maxn];
bool vis[maxn];
void getprime() {
  for (int i = 2; i < maxn; i++) {
    if (!vis[i]) prime[++prime[0]] = i;
    for (int j = 1; j <= prime[0] && i * prime[j] < maxn; j++) {
      vis[i * prime[j]] = 1;
      if (i % prime[j] == 0) break;
    }
  }
  return;
}
int main() {
  getprime();
  long long t, p, q;
  cin >> t;
  while (t--) {
    cin >> p >> q;
    if (p % q != 0) {
      cout << p << '\n';
      continue;
    }
    long long a;
    long long ans = 1;
    for (int i = 1; i <= prime[0]; i++) {
      if (q % prime[i] == 0) {
        int cnt = 0;
        a = p;
        while (q % prime[i] == 0) {
          cnt++;
          q /= prime[i];
        }
        while (a % prime[i] == 0) {
          a /= prime[i];
        }
        for (int j = 1; j < cnt; j++) a *= prime[i];
        ans = max(a, ans);
      }
    }
    if (q > 1) {
      while (p % q == 0) p /= q;
      ans = max(p, ans);
    }
    cout << ans << '\n';
  }
  return 0;
}
