#include <bits/stdc++.h>
#pragma GCC optimize("O2")
using namespace std;
const long long int mod = 1000000007;
const long long int INF64 = mod * mod + 1;
void solve() {
  long long int p, q;
  cin >> p >> q;
  if (p % q) {
    cout << p << '\n';
    return;
  }
  long long int ans = 1;
  for (long long int i = 2; i * i <= q; i++) {
    if (q % i == 0) {
      long long int b = 0;
      long long int temp1 = p, temp2 = q;
      while (p % i == 0) p /= i;
      while (q % i == 0) {
        q /= i;
        b++;
      }
      b--;
      while (b--) p *= i;
      ans = max(ans, p);
      p = temp1, q = temp2;
    }
    if (q % i == 0) {
      long long int b = 0;
      long long int temp1 = p, temp2 = q;
      while (p % (temp2 / i) == 0) p /= (temp2 / i);
      while (q % (temp2 / i) == 0) {
        q /= (temp2 / i);
        b++;
      }
      b--;
      while (b--) p *= (temp2 / i);
      ans = max(ans, p);
      p = temp1, q = temp2;
    }
  }
  if (ans == 1) {
    while (p % q == 0) p /= q;
    ans = max(ans, p);
  }
  cout << ans << '\n';
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int T = 1;
  cin >> T;
  for (long long int i = 1; i <= T; i++) {
    solve();
  }
  cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC
       << "ms\n";
}
