#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(long long n) {
  bool prime[n + 1];
  memset(prime, true, sizeof(prime));
  for (long long p = 2; p * p <= n; p++) {
    if (prime[p] == true) {
      for (long long i = p * p; i <= n; i += p) prime[i] = false;
    }
  }
  for (long long p = 2; p <= n; p++)
    if (prime[p]) cout << p << " ";
}
bool isPrime(long long n) {
  if (n <= 1) return false;
  for (long long i = 2; i * i <= n; i++)
    if (n % i == 0) return false;
  return true;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long a;
  cin >> a;
  long long o = pow(10, 6);
  bool prime[o + 1];
  memset(prime, true, sizeof(prime));
  for (long long p = 2; p * p <= o; p++) {
    if (prime[p] == true) {
      for (long long i = p * p; i <= o; i += p) prime[i] = false;
    }
  }
  while (a--) {
    long long n, m;
    cin >> n >> m;
    vector<long long> v1;
    vector<long long> v2;
    long long z = m;
    for (long long i = 2; i * i <= z; i++) {
      long long count = 0;
      if (prime[i]) {
        while (z % i == 0) {
          z = z / i;
          count++;
        }
        v1.push_back(i);
      }
    }
    if (z > 1) v1.push_back(z);
    for (long long i = 0; i < v1.size(); i++) {
      long long k = n;
      while (k % v1[i] == 0) {
        k = k / v1[i];
        if (k % m != 0) {
          v2.push_back(k);
        }
      }
    }
    if (n % m == 0 && m != 1) {
      sort(v2.begin(), v2.end());
      cout << v2[v2.size() - 1] << "\n";
    } else if ((n % m == 0 && m == 1))
      cout << 1 << "\n";
    else if (n % m != 0)
      cout << n << "\n";
  }
}
