#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 5;
const long long int inf64 = 1e18 + 5;
vector<long long int> get_fact(long long int x) {
  vector<long long int> fact;
  for (int i = 2; i <= sqrt(x); i++) {
    if (x % i == 0) fact.push_back(i);
    while (x % i == 0) x /= i;
  }
  if (x > 1) fact.push_back(x);
  return fact;
}
long long int calc(long long int x, long long int p) {
  long long int res = 1;
  while (p--) res *= x;
  return res;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long int t, a, b;
  cin >> t;
  while (t--) {
    cin >> a >> b;
    if (a < b)
      cout << a << '\n';
    else {
      if (a % b)
        cout << a << '\n';
      else {
        long long int ans = 1;
        vector<long long int> f1 = get_fact(b);
        for (long long int x : f1) {
          long long int p1 = 0, p2 = 0;
          long long int na = a, nb = b;
          while (na % x == 0) {
            ++p1;
            na /= x;
          }
          while (nb % x == 0) {
            ++p2;
            nb /= x;
          }
          long long int rem = p1 - p2 + 1;
          ans = max(ans, a / calc(x, rem));
        }
        cout << ans << '\n';
      }
    }
  }
}
