#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
const int MAXN = (int)1e5 + 5;
const int MOD = (int)1e9 + 7;
const int INF = 0x3f3f3f3f;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
long long eulter_phi(long long x) {
  long long m = (long long)sqrt(x + 0.5);
  long long ans = x;
  for (long long i = 2; i <= m; i++)
    if (x % i == 0) {
      ans = ans / i * (i - 1);
      while (x % i == 0) x /= i;
    }
  if (x > 1) ans = ans / x * (x - 1);
  return ans;
}
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int T;
  cin >> T;
  long long a, m;
  while (T--) {
    cin >> a >> m;
    long long b = gcd(a, m);
    m /= b;
    cout << eulter_phi(m) << endl;
  }
  return 0;
}
