#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
const long long fact_table = 3200008;
priority_queue<long long> pql;
priority_queue<pair<long long, long long>> pqp;
priority_queue<long long, vector<long long>, greater<long long>> pqls;
priority_queue<pair<long long, long long>, vector<pair<long long, long long>>,
               greater<pair<long long, long long>>>
    pqps;
long long dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};
long long dy[8] = {0, 1, 0, -1, -1, 1, 1, -1};
const long long mod = 998244353ll;
long long mypow(long long a, long long b, long long m = mod) {
  long long x = 1;
  while (b) {
    while (!(b & 1)) {
      (a *= a) %= m;
      b >>= 1;
    }
    (x *= a) %= m;
    b--;
  }
  return x;
}
vector<long long> readvec(long long read) {
  vector<long long> res(read);
  for (int i = 0; i < read; i++) {
    cin >> res[i];
  }
  return res;
}
void YES(bool cond) {
  if (cond) {
    cout << "YES" << endl;
    ;
  } else {
    cout << "NO" << endl;
    ;
  }
  return;
}
void Yes(bool cond) {
  if (cond) {
    cout << "Yes" << endl;
    ;
  } else {
    cout << "No" << endl;
    ;
  }
  return;
}
void line() {
  cout << "--------------------" << endl;
  ;
  return;
}
long long mul(long long a, long long b) {
  if (b == 0) return 0;
  if (a > INF / b) return INF;
  return a * b;
}
long long mygcd(long long a, long long b) {
  if (b == 0 || a == b) return a;
  return mygcd(b, a % b);
}
bool icpc = false;
bool multicase = true;
long long n, m, k;
bool solve() {
  long long p, q;
  cin >> p >> q;
  long long ans = 1;
  if (p % q > 0) {
    cout << p << endl;
    ;
    return true;
  } else {
    vector<long long> v;
    for (long long i = 1; i * i <= q; i++) {
      if (q % i == 0) {
        v.push_back(i);
        if (i * i != q) v.push_back(q / i);
      }
    }
    sort(v.begin(), v.end());
    for (auto x : v) {
      if (x == 1) continue;
      long long m = p / q;
      while (m % x == 0) {
        m /= x;
      }
      long long res = (q / x) * m;
      ans = max(ans, res);
    }
    cout << ans << endl;
    ;
    return true;
  }
  return true;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  if (icpc) {
    while (solve())
      ;
    return 0;
  }
  long long q, testcase = 1;
  if (multicase) {
    cin >> q;
  } else {
    q = 1;
  }
  while (q--) {
    solve();
    testcase++;
  }
  return 0;
}
