#include <bits/stdc++.h>
using namespace std;
int main() {
  int T;
  cin >> T;
  while (T--) {
    long long a, b, maxn = 0;
    cin >> a >> b;
    for (int i = 2; i <= sqrt(b); i++) {
      if (b % i != 0) continue;
      long long x = a, y = b, pow = 1;
      while (y % pow == 0) {
        pow *= i;
      }
      pow /= i;
      while (x % pow == 0) {
        x /= i;
      }
      maxn = max(maxn, x);
      pow = 1;
      x = a;
      int t = b / i;
      while (y % pow == 0) {
        pow *= t;
      }
      pow /= t;
      while (x % pow == 0) {
        x /= t;
      }
      maxn = max(maxn, x);
    }
    if (b > 1) {
      long long x = a, y = b, pow = 1;
      while (y % pow == 0) {
        pow *= b;
      }
      pow /= b;
      while (x % pow == 0) {
        x /= b;
      }
      maxn = max(maxn, x);
    }
    cout << maxn << endl;
  }
  return 0;
}
