#include <bits/stdc++.h>
using namespace std;
template <typename T>
using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;
template <class T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
const int INF = 1 << 30;
const long long INFL = 1LL << 60;
const long long mod = 1000000007;
long long gcd(long long x, long long y) {
  if (y == 0) return x;
  return gcd(y, x % y);
}
long long eulerPhi(long long n) {
  if (n == 0) return 0;
  long long ans = n;
  for (long long i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      ans -= ans / i;
      while (n % i == 0) n /= i;
    }
  }
  if (n > 1) ans -= ans / n;
  return ans;
}
void solve() {
  long long a, b;
  cin >> a >> b;
  long long c = gcd(a, b);
  a /= c;
  b /= c;
  cout << eulerPhi(b) << endl;
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int t;
  cin >> t;
  for (int i = 0; i < int(t); i++) {
    solve();
  }
  return 0;
}
