#include <bits/stdc++.h>
using namespace std;
int cases(1), t;
template <typename T>
void binary(T n) {
  stack<int> st;
  while (n > 0) {
    st.push(n % 2);
    n /= 2;
  }
  while (!st.empty()) {
    cout << st.top();
    st.pop();
  }
  cout << '\n';
}
vector<long long> factorize(long long x) {
  vector<long long> res;
  if (x % 2 == 0) {
    res.push_back(2);
  }
  while (x % 2 == 0) {
    x /= 2;
  }
  for (long long i = 3; i * i <= x; i += 2) {
    if (x % i == 0) {
      res.push_back(i);
      while (x % i == 0) {
        x /= i;
      }
    }
  }
  if (x > 2) res.push_back(x);
  return res;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  for (cin >> t; cases <= t; ++cases) {
    long long first, second;
    cin >> first >> second;
    long long ans = 0;
    if (first % second) {
      cout << first << '\n';
      continue;
    }
    vector<long long> fac = factorize(second);
    for (long long i = 0; i < fac.size(); i++) {
      long long res = first;
      while (res % second == 0) {
        res /= fac[i];
      }
      ans = max(res, ans);
    }
    cout << ans << '\n';
  }
  return 0;
}
