#include <bits/stdc++.h>
using namespace std;
const long long int N = 100005;
long long int a, b;
long long int calc(long long int n) {
  if (n == 1) return 1;
  long long int t = a;
  while (t % b == 0) t /= n;
  return t;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int t;
  cin >> t;
  while (t--) {
    long long int i, j, k, n, m, ans = 0, cnt = 0, sum = 0;
    cin >> a >> b;
    if (a % b != 0) {
      cout << a << '\n';
      continue;
    }
    for (i = 1; i * i <= b; i++) {
      if (b % i == 0) {
        sum = b / i;
        ans = max(ans, calc(i));
        ans = max(ans, calc(sum));
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
