#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
const int MAX = 1e5 + 7;
const int mod = 1e9 + 7;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int _;
  cin >> _;
  while (_--) {
    long long p, q, ans = 1, x = 0;
    cin >> p >> q;
    if (p % q != 0)
      ans = p;
    else {
      x = q;
      vector<long long> cnta;
      cnta.push_back(1ll);
      for (long long i = 2; i * i <= q; i++) {
        if (x % i == 0) {
          cnta.push_back(i);
          while (x % i == 0) x /= i;
        }
      }
      if (x > 1) cnta.push_back(x);
      for (long long i = 1; i < cnta.size(); i++) {
        long long k = p;
        while (k % q == 0) k /= cnta[i];
        if (k > ans) ans = k;
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
