#include <bits/stdc++.h>
using namespace std;
long long p, q;
void solve() {
  long long res = 1;
  cin >> p >> q;
  swap(p, q);
  long long a = p;
  for (long long i = 2; i * i <= a; i++)
    if (a % i == 0) {
      long long x = q;
      while (x % i == 0) {
        if (x % p != 0) res = max(res, x);
        x /= i;
      }
      if (x % p != 0) res = max(res, x);
      while (a % i == 0) a /= i;
    }
  if (a > 1) {
    long long x = q;
    while (x % a == 0) {
      if (x % p != 0) res = max(res, x);
      x /= a;
    }
    if (x % p != 0) res = max(res, x);
  }
  cout << res << '\n';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}
