#pragma GCC optimize(3) #include<bits/stdc++.h> #define max(a, b) (a > b ? a : b) #define min(a, b) (a > b ? b : a) typedeflonglong ll; voidreadint(){} template <classT1, class... T2> voidreadint(T1 &i, T2 &... rest) { i = 0; char c; bool f = false; while (!isdigit(c = getchar())) f = c == '-'; do i = (i << 3) + (i << 1) + c - '0'; while (isdigit(c = getchar())); if (f) i = -i; readint(rest...); } usingnamespacestd;
ll solve(ll n, ll m){ vector<ll> p; for (ll i = 2; i * i <= m; ++i) { if (m % i == 0) { p.push_back(i); while (m % i == 0) m /= i; } } if (m > 1) p.push_back(m); ll ret = 0; for (ll s = 1; s < (1 << p.size()); ++s) { ll mult = 1, bits = 0; for (int i = 0; i < p.size(); ++i) { if (s & (1ll << i)) { bits++; mult *= p[i]; } } ll cur = n / mult; if (bits & 1) ret += cur; else ret -= cur; } return n - ret; }
int T;
intmain(){ readint(T); while (T--) { ll a, m; readint(a, m); ll g = __gcd(a, m); ll l = a / g + (a % g != 0), r = (a + m) / g - ((a + m) % g == 0); printf("%I64d\n", solve(r, m / g) - solve(l - 1, m / g)); } return0; }
ll phi(ll n){ ll ret = n; for (ll i = 2; i * i <= n; ++i) { if (n % i == 0) ret = ret / i * (i - 1); while (n % i == 0) n /= i; } if (n > 1) ret = ret / n * (n - 1); return ret; }
intmain(){ cin >> T; while (T--) { ll a, m; cin >> a >> m; ll g = __gcd(a, m); cout << phi(m / g) << endl; } return0; }