#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 100;
const long long mod = 998244353, inf = 1e18;
const long long g = 3;
template <class T>
void Mul(T &x, T y) {
  x = x * y % mod;
}
template <class T>
void Add(T &x, T y) {
  x = (x + y) % mod;
}
template <class T>
void Sub(T &x, T y) {
  x = (x - y + mod) % mod;
}
template <class T>
void Mn(T &x, T y) {
  x = min(x, y);
}
template <class T>
void Mx(T &x, T y) {
  x = max(x, y);
}
long long qpow(long long x, long long y = mod - 2) {
  long long res = 1;
  while (y) {
    if (y & 1) Mul(res, x);
    Mul(x, x), y >>= 1;
  }
  return res;
}
void Div(long long &x, long long y) { Mul(x, qpow(y)); }
int n, m, k, T;
long long gcd(long long x, long long y) { return !y ? x : gcd(y, x % y); }
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> T;
  long long p, q, ans, tmp;
  while (T--) {
    cin >> p >> q;
    if (p < q) {
      cout << p << '\n';
      continue;
    }
    if (p % q != 0) {
      cout << p << '\n';
      continue;
    }
    ans = p;
    while (ans % q == 0) ans /= q;
    for (long long i = 2, j, t; i * i <= q; i++) {
      if (q % i == 0) {
        tmp = p;
        while (tmp % q == 0) tmp /= i;
        ans = max(ans, tmp);
        j = q / i;
        tmp = p;
        while (tmp % q == 0) tmp /= j;
        ans = max(ans, tmp);
      }
    }
    cout << ans << '\n';
  }
}
