#include <bits/stdc++.h>
using namespace std;
bool isprime(long long x) {
  for (long long i = 2; i * i <= x; i++) {
    if (x % i == 0) {
      return false;
    }
  }
  return true;
}
long long gcd(long long a, long long b) {
  if (b == 0) {
    return a;
  } else {
    return gcd(b, a % b);
  }
}
long long eultotient(long long x) {
  long long res = x;
  for (long long i = 2; i * i <= x; i++) {
    if (x % i == 0) {
      while (x % i == 0) {
        x = x / i;
      }
      res = (res / i) * (i - 1);
    }
  }
  if (x > 1) {
    res = (res / x) * (x - 1);
  }
  return res;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long x, y;
    cin >> x >> y;
    long long val = gcd(x, y);
    y = y / val;
    cout << eultotient(y) << "\n";
  }
}
