#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 15;
int prime[maxn];
bool visit[maxn] = {false};
vector<int> prim;
vector<int> nu;
void init() {
  int pos = 0;
  for (int i = 2; i < maxn; i++) {
    if (visit[i] == false) {
      prime[pos++] = i;
    }
    for (int j = 0; j < pos && prime[j] * i < maxn; j++) {
      visit[prime[j] * i] = true;
      if (i % prime[j] == 0) {
        break;
      }
    }
  }
}
bool isprime(long long test) {
  for (int i = 2; i <= sqrt(test); i++) {
    if (test / 2 == 0) {
      return false;
    }
  }
  return true;
}
void find(long long test) {
  for (int i = 0; prime[i] <= sqrt(test); i++) {
    int num = 0;
    while (test % prime[i] == 0) {
      num++;
      test /= prime[i];
    }
    if (num != 0) {
      prim.push_back(prime[i]);
      nu.push_back(num);
    }
  }
  if (isprime(test) && test > 1) {
    prim.push_back(test);
    nu.push_back(1);
  }
}
int main() {
  int t;
  init();
  cin >> t;
  long long p, q;
  while (t--) {
    cin >> p >> q;
    prim.clear();
    nu.clear();
    find(q);
    if (p % q != 0) {
      cout << p << endl;
    } else {
      long long maxans = -100;
      for (int i = 0; i < prim.size(); i++) {
        int tmpnum = 0;
        long long test = p;
        long long ans = p;
        while (test % prim[i] == 0) {
          test /= prim[i];
          tmpnum++;
        }
        int reducenum = tmpnum - nu[i] + 1;
        ans = ans / pow(prim[i], reducenum);
        maxans = max(ans, maxans);
      }
      cout << maxans << endl;
    }
  }
}
