#include <bits/stdc++.h>
using namespace std;
int main() {
  long long t;
  cin >> t;
  while (t--) {
    long long a, b;
    cin >> a >> b;
    if (a % b != 0) {
      cout << a << endl;
    } else {
      long long ans = 1;
      vector<long long> div;
      div.push_back(b);
      for (int i = 2; i * i <= b; i++) {
        if (b % i == 0) {
          div.push_back(i);
          if (i != b / i) {
            div.push_back(b / i);
          }
        }
      }
      for (int i = 0; i < div.size(); i++) {
        if (a % div[i] == 0) {
          long long a1 = a;
          while (a % div[i] == 0) {
            a1 = a1 / div[i];
            if (a1 % b != 0) {
              ans = max(ans, a1);
              break;
            }
          }
        }
      }
      cout << ans << endl;
    }
  }
}
