#include <bits/stdc++.h>
using namespace std;
void seive(vector<long long>& v, long long n) {
  v.push_back(n);
  for (long long i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      v.push_back(i);
      if (i != n / i) v.push_back(n / i);
    }
  }
}
int32_t main() {
  ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  long long t = 1;
  cin >> t;
  while (t--) {
    long long a, b;
    cin >> a >> b;
    if (a % b) {
      cout << a << ("\n");
      ;
    } else {
      vector<long long> v;
      seive(v, b);
      long long ans = 1;
      for (auto i : v) {
        long long tt = a;
        while (tt % i == 0) {
          tt = tt / i;
          if (tt % b != 0) {
            ans = max(ans, tt);
            break;
          }
        }
      }
      cout << ans << ("\n");
    }
  }
  return 0;
}
