#include <bits/stdc++.h>
using namespace std;
const int N = 1e9;
int t, isprime[100000];
long long p, q;
vector<long long> v;
vector<pair<long long, long long> > z;
pair<long long, long long> tmp;
void sieve() {
  for (int i = 0; i <= sqrt(N); i++) isprime[i] = true;
  isprime[0] = isprime[1] = false;
  for (int i = 2; i <= sqrt(N); i++) {
    if (isprime[i]) {
      v.push_back(i);
      for (int j = i + i; j <= sqrt(N); j += i) {
        isprime[j] = false;
      }
    }
  }
}
int main() {
  cin >> t;
  sieve();
  while (t--) {
    cin >> p >> q;
    long long go = q;
    z.clear();
    for (int i = 0; i < v.size(); i++) {
      int ok = 0;
      while (q % v[i] == 0) {
        ok++;
        q /= v[i];
      }
      if (ok) {
        z.push_back({v[i], ok});
      }
    }
    if (q != 1) {
      z.push_back({q, 1});
    }
    if (p % go != 0) {
      cout << p << endl;
    } else {
      long long ans = 0;
      for (int i = 0; i < z.size(); i++) {
        tmp = z[i];
        long long lin = p, zz = tmp.first, cnt = tmp.second - 1;
        while (lin % zz == 0) {
          lin /= zz;
        }
        while (cnt--) {
          lin *= zz;
        }
        ans = max(ans, lin);
      }
      cout << ans << endl;
    }
  }
}
