#include <bits/stdc++.h>
using namespace std;
long long t, p, q, pre[200000 + 5], k, vis[200000 + 5];
void init() {
  for (long long i = 2; i <= 200000 + 5; i++) {
    if (!vis[i]) {
      vis[i] = 1;
      pre[++k] = i;
      for (long long j = i; j * i <= 200000 + 5; j++) vis[i * j] = 1;
    }
  }
}
int main(void) {
  std::ios::sync_with_stdio(false);
  init();
  cin >> t;
  while (t--) {
    cin >> p >> q;
    if (p % q) {
      cout << p << endl;
      continue;
    }
    long long ans = 1, temp = q;
    for (long long i = 1; i <= k; i++) {
      long long tot = 0, res = 1;
      while (temp % pre[i] == 0) {
        temp /= pre[i];
        tot++;
        res *= pre[i];
      }
      if (!tot) continue;
      res /= pre[i];
      if (p % res == 0) {
        long long temp1 = p;
        while (temp1 % pre[i] == 0) temp1 /= pre[i];
        ans = max(ans, res * temp1);
      }
    }
    if (temp > 1) {
      long long res = 1;
      if (p % res == 0) {
        long long temp1 = p;
        while (temp1 % temp == 0) temp1 /= temp;
        ans = max(ans, res * temp1);
      }
    }
    cout << ans << endl;
  }
  return 0;
}
