#include <bits/stdc++.h>
using namespace std;
const long long Mod = 4e18;
long long poww(long long a, long long b, long long Mod) {
  long long res = 1;
  if (b < 0) b = (b % (Mod - 1) + Mod - 1) % (Mod - 1);
  for (; b; b >>= 1, a = 1ll * a * a % Mod)
    if (b & 1) res = 1ll * res * a % Mod;
  return res;
}
vector<long long> v;
map<long long, long long> m;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) {
    v.clear();
    m.clear();
    long long a, b;
    cin >> a >> b;
    if (a % b != 0) {
      cout << a << '\n';
      continue;
    }
    long long B = b;
    for (int i = 2; i * i <= B; i++) {
      if (B % i == 0) {
        v.push_back(i);
        while (B % i == 0) {
          m[i]++;
          B /= i;
        }
      }
    }
    if (B != 1) {
      v.push_back(B);
      m[B]++;
    }
    long long ans = 1;
    for (auto r : v) {
      long long x = a;
      while (x % r == 0) x /= r;
      x *= poww(r, m[r] - 1, Mod);
      ans = max(ans, x);
    }
    cout << ans << '\n';
  }
  return 0;
}
