#include <bits/stdc++.h>
using namespace std;
long long fun(long long a, long long b) {
  while (a % b == 0) {
    a /= b;
  }
  return a;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long a, b, ans = 1;
    cin >> a >> b;
    if (a % b != 0) {
      cout << a << endl;
    } else {
      long long m;
      ans = fun(a, b);
      for (int i = 2; i * i <= b; ++i) {
        if (b % i == 0) {
          m = a;
          while (m % b == 0) {
            m /= i;
          }
          ans = max(ans, m);
          m = a;
          long long d = b / i;
          while (m % b == 0) {
            m /= d;
          }
          ans = max(ans, m);
        }
      }
      cout << ans << endl;
    }
  }
  return 0;
}
