#include <bits/stdc++.h>
using namespace std;
vector<long long> prime;
vector<bool> vis(1e5 + 1000, true);
void sieve(long long n) {
  prime.push_back(2);
  for (long long i = 4; i <= n; i += 2) {
    vis[i] = false;
  }
  for (long long i = 3; i <= n; i += 2) {
    if (vis[i]) {
      prime.push_back(i);
      if (i > sqrt(n)) {
        continue;
      }
      for (long long j = i * i; j <= n; j += 2 * i) {
        vis[j] = false;
      }
    }
  }
}
int main() {
  sieve(100100);
  int t;
  cin >> t;
  for (int tc = 1; tc <= t; tc++) {
    long long p, q;
    cin >> p >> q;
    if (p % q != 0) {
      cout << p << '\n';
      continue;
    }
    vector<long long> factor, power;
    for (int i = 0; prime[i] <= sqrt(q); i++) {
      if (q % prime[i] == 0) {
        factor.push_back(prime[i]);
        long long cur = 0;
        while (q % prime[i] == 0) {
          cur++;
          q /= prime[i];
        }
        power.push_back(cur);
      }
    }
    if (q != 1) {
      factor.push_back(q);
      power.push_back(1);
    }
    long long ans = 0;
    for (int i = 0; i < factor.size(); i++) {
      long long r = factor[i];
      long long cur = p;
      while (cur % r == 0) {
        cur /= r;
      }
      for (long long j = 1; j < power[i]; j++) {
        cur *= r;
      }
      ans = max(ans, cur);
    }
    cout << ans << '\n';
  }
}
