#include <bits/stdc++.h>
using namespace std;
long long t, p, q;
long long pri[100005];
vector<long long> arr;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> t;
  for (long long i = 2; i <= 100000; i++) {
    if (!pri[i]) {
      arr.push_back(i);
      for (long long j = 2; j <= 100000 / i; j++) pri[i * j] = 1;
    }
  }
  while (t--) {
    cin >> p >> q;
    if (p % q)
      cout << p << '\n';
    else {
      long long ans = 1, qi = q;
      bool bl = 1;
      for (auto i : arr) {
        long long pi = p, num1 = 1, num2 = 1;
        while (pi % i == 0) pi /= i, num1 *= i;
        while (q % i == 0) q /= i, num2 *= i;
        if (num2 > 1) {
          num2 /= i;
          bl = 0;
          ans = max(ans, p / num1 * num2);
        }
      }
      long long pi = p, num1 = 1, num2 = 1;
      while (pi % qi == 0) pi /= qi, num1 *= qi;
      ans = max(ans, p / num1);
      cout << ans << '\n';
    }
  }
  return 0;
}
