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