#include <bits/stdc++.h>
using namespace std;
long long euler(long long n) {
  long long res = n, a = n;
  for (int i = 2; (long long)i * i <= a; i++) {
    if (a % i == 0) {
      res = res / i * (i - 1);
      while (a % i == 0) a /= i;
    }
  }
  if (a > 1) res = res / a * (a - 1);
  return res;
}
long long gcd(long long a, long long b) { return a == 0 ? b : gcd(b % a, a); }
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    long long a, m;
    scanf("%lld%lld", &a, &m);
    long long t = gcd(a, m);
    a /= t;
    m /= t;
    cout << euler(m) << endl;
  }
  return 0;
}
