#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
map<int, int> mp;
void solve(int x) {
  for (int i = 2; i <= x / i; i++) {
    int cnt = 0;
    if (x % i == 0) {
      while (x % i == 0) x /= i, cnt++;
      mp[i] = cnt;
    }
  }
  if (x != 1) {
    mp[x] = 1;
  }
}
long long pow(int x, int y) {
  long long ans = 1;
  while (y) {
    if (y & 1) ans = ans * x;
    x = x * x;
    y /= 2;
  }
  return ans;
}
long long ask(long long n, long long m) {
  while (n % m == 0) {
    n /= m;
  }
  return n;
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    mp.clear();
    long long n;
    int m;
    scanf("%lld %d", &n, &m);
    if (n % m != 0) {
      printf("%lld\n", n);
    } else {
      solve(m);
      long long ans = 0;
      map<int, int>::iterator it;
      for (it = mp.begin(); it != mp.end(); it++) {
        int x = it->first, y = it->second;
        long long tmp = n, tmp1 = 1;
        while (tmp % x == 0) tmp /= x;
        tmp1 = tmp;
        for (int i = 1; i < y; i++) {
          tmp1 *= x;
        }
        ans = max(ans, tmp1);
      }
      printf("%lld\n", ans);
    }
  }
}
