#include <bits/stdc++.h>
using namespace std;
long long power(long long a, long long b) {
  if (!b) return 1;
  long long aa = power(a, b / 2);
  if (b % 2) return aa * aa * a;
  return aa * aa;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    long long p, q;
    cin >> p >> q;
    if (p % q != 0) {
      cout << p << endl;
      continue;
    }
    map<long long, long long> m;
    long long tem = q;
    while (tem % 2 == 0) {
      m[2]++;
      tem /= 2;
    }
    for (long long i = 3; i <= sqrt(tem); i += 2) {
      while (tem % i == 0) {
        m[i]++;
        tem /= i;
      }
      if (tem == 1) break;
    }
    if (tem > 2) m[tem]++;
    long long ans = 0;
    for (auto a : m) {
      long long c = 0;
      long long temp = p;
      while (temp % a.first == 0) {
        c++;
        temp /= a.first;
      }
      ans = max(ans, p / power(a.first, c - a.second + 1));
    }
    cout << ans << endl;
  }
  return 0;
}
