#include <bits/stdc++.h>
using namespace std;
const long long int MOD = 1e9 + 7;
long long int power(long long int x, long long int y) {
  if (y == 0) return 1;
  long long int temp = power(x, y / 2);
  if (y % 2 == 0)
    return temp * temp;
  else
    return ((x * temp) * temp);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int t = 1;
  cin >> t;
  while (t--) {
    long long int p, q, i, j;
    cin >> p >> q;
    std::map<long long int, long long int> m;
    long long int q1 = q;
    for (i = 2; i * i <= q; i++) {
      if (q1 % i == 0) {
        long long int x = 0;
        while (q1 % i == 0) q1 /= i, x++;
        m[i] = x;
      }
    }
    if (q1 > 1) m[q1] = 1;
    std::map<long long int, long long int> fac;
    pair<long long int, long long int> z = {-1, -1};
    long long int mn = 1e18, f = 0;
    for (auto x : m) {
      long long int num = 0;
      while (p % x.first == 0) {
        num++;
        p /= x.first;
      }
      if (num >= x.second) {
        if (power(x.first, num - x.second + 1) < mn) {
          mn = power(x.first, num - x.second + 1);
          z = {x.first, x.second - 1};
        }
      } else
        f = 1;
      fac[x.first] = num;
    }
    long long int ans = 1;
    for (auto x : fac) {
      if (f == 0 && z.first == x.first) {
        ans *= power(z.first, z.second);
      } else
        ans *= power(x.first, x.second);
    }
    ans *= p;
    cout << ans << "\n";
  }
  cerr << "Time Taken:" << (float)clock() / CLOCKS_PER_SEC * 1000 << "ms"
       << "\n";
  return 0;
}
