#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, m;
    cin >> n >> m;
    if (n % m != 0) {
      cout << n << endl;
      continue;
    } else {
      long long l = -1;
      vector<long long> v;
      v.push_back(m);
      for (long long i = 2; i * i <= m; i++) {
        if (m % i == 0) {
          if (m / i == i) {
            v.push_back(i);
          } else {
            v.push_back(m / i);
            v.push_back(i);
          }
        }
      }
      long long ans = 0;
      for (long long i = 0; i < v.size(); i++) {
        if (n % v[i] == 0) {
          long long temp = n;
          while (temp % v[i] == 0) {
            temp = temp / v[i];
            if (temp % m != 0) {
              ans = max(ans, temp);
            }
          }
        }
      }
      cout << ans << endl;
    }
  }
}
