#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long aa, bb;
    cin >> aa >> bb;
    if (aa % bb != 0) {
      cout << aa << endl;
      continue;
    }
    long long ans = 1;
    vector<long long> jj;
    for (long long i = 1; i * i <= bb; i++) {
      if (bb % i == 0) {
        jj.push_back(bb / i);
        jj.push_back(i);
      }
    }
    for (auto i : jj) {
      if (i == 1) {
        continue;
      }
      long long st = 0;
      for (long long j = 2; j * j <= i; j++) {
        if (i % j == 0) {
          st = 1;
          break;
        }
      }
      if (st) {
        continue;
      }
      long long co = 0;
      long long dd = aa;
      while (dd % i == 0) {
        co++;
        dd /= i;
      }
      long long co2 = 0;
      dd = bb;
      while (dd % i == 0) {
        co2++;
        dd /= i;
      }
      long long kk = 1;
      for (long long j = 0; j < max(co - co2 + 1, (long long)0); j++) {
        kk *= i;
      }
      ans = max(ans, aa / (kk));
    }
    cout << ans << endl;
  }
  return 0;
}
