#include <bits/stdc++.h>
using namespace std;
struct node {
  long long int a, b;
};
bool compare(node x, node y) { return x.a > y.a; }
void printDivisors(int n) {
  for (int i = 1; i <= n; i++)
    if (n % i == 0) printf("%d ", i);
}
long long int maxSum(vector<long long int> x) {
  long long int cur_sum = 0;
  long long int max_sum = 0;
  for (long long int i = 0; i < x.size(); i++) {
    cur_sum += x[i];
    if (max_sum < cur_sum) max_sum = cur_sum;
    if (cur_sum < 0) cur_sum = 0;
  }
  return max_sum;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  long long int t;
  cin >> t;
  while (t--) {
    long long int p, q;
    cin >> p >> q;
    ;
    if (p < q || p % q)
      cout << p << "\n";
    else {
      vector<long long int> v;
      for (long long int i = 1; i <= sqrt(q); i++) {
        if (q % i == 0) {
          v.push_back(i);
          if (i != q / i) v.push_back(q / i);
        }
      }
      long long int res = 1;
      sort(v.begin(), v.end(), greater<long long int>());
      for (long long int i = 0; i < v.size() - 1; i++) {
        long long int x = p;
        while (x % v[i] == 0) {
          if (x < q || x % q)
            break;
          else
            x /= v[i];
        }
        res = max(res, x);
      }
      cout << res << "\n";
    }
  }
  return 0;
}
