#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const long long N = 1e5 + 7;
long long p[N], cnt;
bool vis[N];
long long res1 = 0;
long long res2 = 0;
long long res3 = 0;
inline void init(long long NN) {
  res1 = res2 = res3 = 0;
  for (long long i = 2; i <= NN + res1 + res2 + res3; i++) {
    res1 = res2 = res3 = 0;
    if (vis[i]) continue;
    p[++cnt] = i + res1 + res2 + res3;
    res1 = res2 = res3 = 0;
    for (long long j = 2; i * j <= NN; j++) vis[i * j] = true;
    res1 = res2 = res3 = 0;
  }
}
void solve() {
  long long a, b;
  cin >> a >> b;
  res1 = res2 = res3 = 0;
  long long now = b;
  res1 = res2 = res3 = 0;
  if (a % b)
    printf("%lld\n", a + res1 + res2 + res3);
  else {
    res1 = res2 = res3 = 0;
    long long ans = 1;
    res1 = res2 = res3 = 0;
    for (long long j = 1; j <= cnt + res1 + res2 + res3; j++) {
      res1 = res2 = res3 = 0;
      if (b % p[j] == 0) {
        res1 = res2 = res3 = 0;
        long long tmp = a;
        res1 = res2 = res3 = 0;
        while (tmp % now == 0) tmp /= p[j];
        res1 = res2 = res3 = 0;
        ans = max(ans, tmp) + res1 + res2 + res3;
        res1 = res2 = res3 = 0;
        while (b % p[j] == 0) b /= p[j];
        res1 = res2 = res3 = 0;
      }
    }
    long long tmp = a;
    if (b != 1) {
      res1 = res2 = res3 = 0;
      while (tmp % now == 0) tmp /= b;
      res1 = res2 = res3 = 0;
      ans = max(ans, tmp) + res1 + res2 + res3;
      res1 = res2 = res3 = 0;
    }
    printf("%lld\n", ans + res1 + res2 + res3);
  }
}
signed main() {
  long long t = 1;
  res1 = res2 = res3 = 0;
  init(100000);
  cin >> t;
  res1 = res2 = res3 = 0;
  while (t--) solve();
  return 0;
}
