#include <bits/stdc++.h>
using namespace std;
const int64_t Nmax = 1e9 + 7;
const int64_t mod = 1000000007;
vector<int64_t> prime;
int64_t is_power_of_two(int64_t a) { return a && (!(a & (a - 1))); }
int64_t isperfectsquare(int64_t a) {
  double b = sqrt(a);
  return (b - ceil(b) == 0);
}
int64_t pow(int64_t a, int64_t b, int64_t m) {
  a = a % m;
  int64_t res = 1;
  while (b > 0) {
    if (b & 1) {
      res = res * a % m;
    }
    a = a * a % m;
    b = b / 2;
  }
  return res;
}
void seive(int64_t n) {
  bool isprime[n];
  memset(isprime, true, sizeof(isprime));
  prime.push_back(2);
  for (int64_t i = 3; i <= sqrt(n); i += 2) {
    if (isprime[i]) {
      for (int64_t j = i * i; j <= n; j += i) {
        isprime[j] = false;
      }
    }
  }
  for (int64_t i = 3; i <= n; i += 2) {
    if (isprime[i]) {
      prime.push_back(i);
    }
  }
}
vector<pair<int64_t, int64_t> > factors(int64_t n) {
  vector<pair<int64_t, int64_t> > fact_expo;
  for (int64_t i = 2; i <= sqrt(n); i++) {
    if (n % i == 0) {
      int64_t exp = 0;
      while (n % i == 0) {
        n = n / i;
        exp++;
      }
      fact_expo.push_back({i, exp});
    }
  }
  if (n > 1) {
    fact_expo.push_back({n, 1});
  }
  return fact_expo;
}
void solve() {
  int64_t n, k;
  cin >> n >> k;
  if (n % k) {
    cout << n << "\n";
    return;
  }
  int64_t ans = -1;
  vector<pair<int64_t, int64_t> > fact = factors(k);
  for (auto e : fact) {
    int64_t temp = n;
    while (temp % e.first == 0) {
      temp /= e.first;
    }
    ans = max(ans, (int64_t)(temp * pow(e.first, e.second - 1)));
  }
  cout << ans << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int64_t t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
