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