#include <bits/stdc++.h>
#include <cstdint>

using namespace std;
using ll = int64_t;

ll cgcd(ll a, ll b){
    while(b){
        ll temp = a % b;
        a = b;
        b = temp;
    }
    return a;
}

ll phi(ll n){
    if(n == 0) return 0;
    ll res = n;
    for(ll p=2; p*p <= n; p++){
        if(n % p == 0){
            while(n % p ==0){
                n /= p;
            }
            res -= res / p;
        }
    }
    if(n > 1){
        res -= res / n;
    }
    return res;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int T;
    cin >> T;
    while(T--){
        ll a, m;
        cin >> a >> m;
        ll d = cgcd(a, m);
        ll mp = m / d;
        ll ans = phi(mp);
        cout << ans << "\n";
    }
}