#include <bits/stdc++.h>
const long long int M = 1e9 + 7;
const long long int inf = 1e18 + 5;
using namespace std;
long long int power(long long int a, long long int n, long long int p) {
  long long int res = 1;
  a = a % p;
  while (n > 0) {
    if (n & 1) res = (res * a) % p;
    n = n >> 1;
    a = (a * a) % p;
  }
  return res;
}
void sieve(vector<long long int>& v, long long int n) {
  v.push_back(n);
  for (long long int i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      v.push_back(i);
      if (i != n / i) v.push_back(n / i);
    }
  }
}
long long int solve() {
  long long int p, q, ans = 1;
  cin >> p >> q;
  if (p % q)
    return p;
  else {
    vector<long long int> v;
    sieve(v, q);
    for (auto i : v) {
      long long int s = p;
      while (s % i == 0) {
        s /= i;
        if (s % q != 0) {
          ans = max(ans, s);
          break;
        }
      }
    }
    return ans;
  }
  return 0;
}
int main() {
  cin.tie(0);
  cout.tie(0);
  ios_base::sync_with_stdio(0);
  ;
  long long int t = 1;
  cin >> t;
  while (t--) cout << solve() << "\n";
  return 0;
}
