#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 100005;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  long long p, q;
  cin >> t;
  while (t--) {
    cin >> p >> q;
    if ((q > p) || (p % q != 0)) {
      cout << p << '\n';
    } else {
      long long ans = 0;
      for (long long i = 1; i <= sqrt(q); i++) {
        if (q % i == 0) {
          long long m = p;
          while (m == (m / i) * i && m != 1 && i != 1) {
            m /= i;
            if (m % q != 0) {
              ans = max(ans, m);
            }
          }
          m = p;
          while (m == ((m / (q / i)) * (q / i)) && m != 1) {
            m /= (q / i);
            if (m % q != 0) {
              ans = max(ans, m);
            }
          }
        }
      }
      cout << ans << '\n';
    }
  }
}
