#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
long long T, P, Q, q;
void solve() {
  long long ans = 0;
  cin >> P >> Q;
  q = Q;
  for (long long i = 2; i * i <= Q; i++) {
    if (q % i) continue;
    while (q % i == 0) q /= i;
    long long p = P;
    while (p % Q == 0) p /= i;
    ans = max(ans, p);
  }
  if (q > 1) {
    long long p = P;
    while (p % Q == 0) p /= q;
    ans = max(ans, p);
  }
  cout << ans << "\n";
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> T;
  while (T--) solve();
  return 0;
}
