#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MX = 1e9;
bool is_prime(ll x) {
  if (x < 2) return false;
  if (x == 2) return true;
  for (ll i = 2; i * i <= x; ++i) {
    if (x % i == 0) return false;
  }
  return true;
}
vector<ll> f(ll x) {
  vector<ll> res;
  for (ll i = 1; i * i <= x; ++i) {
    if (x % i == 0) {
      res.push_back(i);
      ll j = x / i;
      if (x % j == 0 && j != i) {
        res.push_back(j);
      }
    }
  }
  return res;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int t;
  cin >> t;
  while (t--) {
    ll p, q;
    cin >> p >> q;
    if (p < q || p % q != 0) {
      cout << p << '\n';
      continue;
    }
    if (p <= MX) {
      auto d = f(p);
      ll res = 1;
      for (ll x : d) {
        if (x % q != 0) res = max(res, x);
      }
      cout << res << '\n';
    } else {
      ll res = p;
      while (res % q == 0) res /= q;
      for (ll i = 1; i <= 1e5; ++i) {
        if (p % i == 0) {
          if (i % q != 0) {
            res = max(i, res);
          }
          ll x = p;
          while (i > 1 && x > 0) {
            if (p % x == 0 && x % q != 0) {
              res = max(x, res);
            }
            x /= i;
          }
        }
      }
      cout << res << '\n';
    }
  }
}
