#include <bits/stdc++.h>
const long long MOD = 1e9 + 7;
using namespace std;
void solve() {
  long long p, q, Ans = 1;
  cin >> p >> q;
  if (p % q) {
    cout << p << "\n";
    ;
    return;
  }
  long long x = p;
  while (x % q == 0) x /= q;
  Ans = x;
  for (long long i = 2; i * i <= q; i++) {
    if (q % i) continue;
    long long x = p, j = q / i;
    while (x % q == 0) x /= i;
    Ans = max(Ans, x);
    x = p;
    while (x % q == 0) x /= j;
    Ans = max(Ans, x);
  }
  cout << Ans << "\n";
  ;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
