#include <bits/stdc++.h>
using namespace std;
const long long N = 1000006, INF = 1e18, MOD = 1e9 + 7;
long long n, m, r, t, a[N], b[N], c[N], q = 1, e, o, u, k, x, y, ans, Ans[N],
                                        mx;
vector<long long> v[N];
string s, ss[N];
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0);
  cin >> q;
  while (q--) {
    ans = x = y = o = u = 0;
    e = INF;
    cin >> x >> y;
    if (x % y)
      cout << x << endl;
    else {
      k = sqrt(y);
      for (int i = 1; i <= k; i++) {
        if (y % i == 0) {
          if (i > 1) {
            u = x;
            while (u % y == 0) u /= i;
            ans = max(ans, u);
          }
          u = x;
          o = y / i;
          while (u % y == 0) u /= o;
          ans = max(ans, u);
        }
      }
      cout << max(ans, (long long)1) << endl;
    }
  }
}
