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