#include <bits/stdc++.h>
using namespace std;
long long power(long long a, long long b) {
  long long res = 1;
  a = a % 1000000007;
  while (b > 0) {
    if (b & 1) {
      res = (res * a) % 1000000007;
      b--;
    }
    a = (a * a) % 1000000007;
    b >>= 1;
  }
  return res;
}
long long fermat_inv(long long y) { return power(y, 1000000007 - 2ll); }
long long gcd(long long a, long long b) { return (b == 0) ? a : gcd(b, a % b); }
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t = 1;
  cin >> t;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    if (p < q)
      cout << p << "\n";
    else if (gcd(p, q) < q)
      cout << p << "\n";
    else {
      long long ans = 1;
      long long fac = p;
      for (long long i = 2; i * i <= q; i++) {
        int ctr = 0;
        long long val = 1ll;
        while (q % i == 0) {
          q /= i;
          ctr++;
        }
        long long p1 = p;
        int ctr1 = 0;
        while (p1 % i == 0) {
          p1 /= i;
          ctr1++;
          if (ctr1 >= ctr) val *= i;
        }
        if (ctr > 0) fac = min(fac, val);
      }
      if (q > 1) {
        long long p1 = p;
        long long val = 1ll;
        while (p1 % q == 0) {
          p1 /= q;
          val *= q;
        }
        fac = min(fac, val);
      }
      ans = max(ans, p / fac);
      cout << ans << "\n";
    }
  }
  return 0;
}
