Problem:
Problem E
最大公約数
正の整数
M
,
A
が与えられる．整数
x
が以下の条件をすべて満たすとき，
x
は良い整数である．良い整数の個数を求めよ．
1 ≤ x < M
．
M
と
x
は互いに素．
M
と
A
の最大公約数を
g
とするとき，
Ax ≡ g (mod M)
．
Input
入力は
500
個以下のデータセットからなる．各データセットは次の形式で表される．
M
A
各データセットは整数
M
と
A
を含む 1 行からなる．
2 ≤ M ≤ 10
12
および
1 ≤ A < M
を満たすことが保証される．
入力の終わりは 2 つのゼロからなる行で表される．
Output
各データセットに対し，良い整数の個数を 1 行に出力せよ．
Sample Input
6 4
5040 128
1000000000000 500000000000
0 0
Output for the Sample Input
1
8
400000000000

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define rep2(i, m, n) for (int i = (m); i < (n); ++i)
#define rep(i, n) rep2(i, 0, n)
#define drep2(i, m, n) for (int i = (m)-1; i >= (n); --i)
#define drep(i, n) drep2(i, n, 0)
#define all(...) std::begin(__VA_ARGS__), std::end(__VA_ARGS__)
#define rall(...) std::rbegin(__VA_ARGS__), std::rend(__VA_ARGS__)
#define FOR(i, a, b) for (int i = (a), i##_len = (b); i <= i##_len; ++i)
#define REV(i, a, b) for (int i = (a); i >= (b); --i)
#define CLR(a, b) memset((a), (b), sizeof(a))
#define DUMP(x) cout << #x << " = " << (x) << endl;
#define INF 1001001001001001001ll
#define inf (int)1001001000
#define MOD 998244353
#define MOD1 1000000007
#define PI 3.14159265358979
#define Dval 1e-12
#define fcout cout << fixed << setprecision(12)
#define Mp make_pair
#define pb push_back
#define fi first
#define se second
#define SORT(x) sort(x.begin(),x.end())
#define ERASE(x) x.erase(unique(x.begin(),x.end()),x.end())
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin())
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin())

using ll = long long;
using ld = long double;
using vi = vector<int>;
using vl = vector<long long>;
using vs = vector<string>;
using vd = vector<double>;
using vld = vector<long double>;
using vc = vector<char>;
using vb = vector<bool>;
using vpii = vector<pair<int, int>>;
using vpil = vector<pair<int, long long>>;
using vpll = vector<pair<long long, long long>>;
using vvi = vector<vector<int>>;
using vvl = vector<vector<long long>>;
using vvd = vector<vector<double>>;
using vvld = vector<vector<long double>>;
using vvc = vector<vector<char>>;
using vvb = vector<vector<bool>>;
using vvpii = vector<vector<pair<int,int>>>;
using vvpll = vector<vector<pair<long long,long long>>>;
using vvvi = vector<vector<vector<int>>>;
using vvvl = vector<vector<vector<long long>>>;
using pii = pair<int, int>;
using pll = pair<long long, long long>;
using LL = __int128_t;

template<typename T>
T dgt(T b, T n){ T cnt=0; while(n){ cnt++; n/=b;} return cnt;}
ll gcd(ll x, ll y) {	if (x == 0) return y;	return gcd(y%x, x);} ll lcm(ll x, ll y) { __int128_t xx,yy; xx=x; yy=y; __int128_t ans=xx * yy / gcd(x, y); ll ans2=ans; return ans; }
template<typename T>
T POW(T x, ll n){T ret=1;	while(n>0){		if(n&1) ret=ret*x;		x=x*x;		n>>=1;	}	return ret;}
template<typename T>
T modpow(T a, ll n, T p) {	if(n==0) return (T)1;  if (n == 1) return a % p;  if (n % 2 == 1) return (a * modpow(a, n - 1, p)) % p;  T t = modpow(a, n / 2, p);  return (t * t) % p;}
template<typename T>
T modinv(T a, T m) {	if(m==0)return (T)1;	T b = m, u = 1, v = 0;	while (b) {		T t = a / b;		a -= t * b; swap(a, b);		u -= t * v; swap(u, v);	}	u %= m;	if (u < 0) u += m;	return u;}
template<typename T>
T REM(T a, T b){ return (a % b + b) % b;}
template<typename T>
T QUO(T a, T b){ return (a - REM(a, b)) / b;}
const int MAXCOMB=510000;
ll MODCOMB = 998244353;
ll fac[MAXCOMB], finv[MAXCOMB], inv[MAXCOMB]; 
void COMinit() {	fac[0] = fac[1] = 1;	finv[0] = finv[1] = 1;	inv[1] = 1;	for (int i = 2; i < MAXCOMB; i++) {		fac[i] = fac[i - 1] * i % MODCOMB;		inv[i] = MODCOMB - inv[MODCOMB%i] * (MODCOMB / i) % MODCOMB;		finv[i] = finv[i - 1] * inv[i] % MODCOMB;	}}
ll COM(ll n, ll k) {	if (n < k) return 0;	if (n < 0 || k < 0) return 0;	return fac[n] * (finv[k] * finv[n - k] % MODCOMB) % MODCOMB;}
ll com(ll n,ll m){   if(n<m || n<=0 ||m<0){		return 0;	}	if( m==0 || n==m){		return 1;	}	ll k=1;	for(ll i=1;i<=m;i++){       k*=(n-i+1); 	   k%=MODCOMB;	   k*=modinv(i,MODCOMB);	   k%=MODCOMB;	}	return k;}
ll rad(ll u, ll p){ ll cnt=0;	while(u%p==0){		u/=p;		cnt++;	}	return cnt;}

template <typename T> inline bool chmax(T &a, T b) { return ((a < b) ? (a = b, true) : (false));}
template <typename T> inline bool chmin(T &a, T b) { return ((a > b) ? (a = b, true) : (false));}
template <class T> T BS(vector<T> &vec, T key) { auto itr = lower_bound(vec.begin(), vec.end(), key); return distance(vec.begin(), itr); }
template<class T> pair<T,T> RangeBS(vector<T> &vec, T lowv, T highv){auto itr_l = lower_bound(vec.begin(), vec.end(), lowv); auto itr_r = upper_bound(vec.begin(), vec.end(), highv); return make_pair(distance(vec.begin(), itr_l), distance(vec.begin(), itr_r)-1);}
void fail() { cout << "-1\n"; exit(0); } void no() { cout << "No\n"; exit(0); } void yes() { cout << "Yes\n"; exit(0); }
template<class T> void er(T a) { cout << a << '\n'; exit(0); }
int dx[] = { 1,0,-1,0,1,1,-1,-1,0 }; int dy[] = { 0,1,0,-1,1,-1,1,-1,0 };
bool range_in(int i, int j, int h, int w){ if(i<0 || j<0 || i>=h || j>=w) return false; return true;} 
int bitcount(int n){n=(n&0x55555555)+(n>>1&0x55555555); n=(n&0x33333333)+(n>>2&0x33333333); n=(n&0x0f0f0f0f)+(n>>4&0x0f0f0f0f); n=(n&0x00ff00ff)+(n>>8&0x00ff00ff); n=(n&0x0000ffff)+(n>>16&0x0000ffff); return n;}

vector<pair<ll, ll>> prime_factor(ll n) {
    vector<pair<ll, ll>> ret;
    for (ll i = 2; i * i <= n; i++) {
        if (n % i != 0) continue;
        ll tmp = 0;
        while (n % i == 0) {
            tmp++;
            n /= i;
        }
        ret.push_back(make_pair(i, tmp));
    }
    if (n != 1) ret.push_back(make_pair(n, 1));
    return ret;
}

ll Random(ll upper) {
    static mt19937_64 engine(chrono::steady_clock::now().time_since_epoch().count());
    uniform_int_distribution<ll> dist(1, upper);
    return dist(engine);
}

void solve(int &FIN){
    ll M,A;
    cin>>M>>A;
    if(M==0){
        FIN=1;
        return;
    }
    // M=Random(10);
    // A=Random(M);
    ll g=gcd(M,A);
    //cout<<g<<endl;
    ll m=M/g;
    ll a=A/g;
    vpll fact=prime_factor(m);
    ll val=1;
    rep(i,fact.size()){
        while(g%fact[i].fi==0){
            g/=fact[i].fi;
            val*=fact[i].fi;
        }
    }
    ll g2=g;
    g=g*val;

    vpll fact2=prime_factor(g2);
    rep(i,fact2.size()){
        g/=fact2[i].fi;
        g*=fact2[i].fi-1;
    }
    // ll ans=0;
    // for(ll x=1;x<M;x++){
    //     ll G=gcd(M,A);
    //     if(gcd(M,x)!=1)continue;
    //     if((A*x-G)%M==0)ans++;
    // }
    // // if(ans!=g){
    // //     cout<<M<<" "<<A<<" "<<ans<<" "<<g<<endl;
    // //     assert(0==1);
    // // }
    // //cout<<"A"<<endl;
    cout<<g<<endl;

}

signed main(){
	cin.tie(0);
	ios::sync_with_stdio(0);
	cout<<fixed<<setprecision(20);
    int FIN=0;
	while(1){
        solve(FIN);
        if(FIN)return 0;
    }
}
accuracy: 1
time_ms: 210
memory_kb: 3348
final_rank: 14

code_snippet: #ifdef LOCAL
#define _GLIBCXX_DEBUG
#pragma GCC optimize("O0")
#else
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#endif

#include <bits/stdc++.h>
// #include <bits/extc++.h>
using namespace std;

// #include <atcoder/modint>
// using mint = atcoder::modint998244353;
// istream& operator>>(istream& in, mint& x) {
//     long long a;
//     in >> a;
//     x = a;
//     return in;
// }
// ostream& operator<<(ostream& out, const mint& x) {
//     return out << x.val();
// }

using ll = long long;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
using u128 = unsigned __int128;
using f128 = __float128;

template <class T>
constexpr T infty = 0;
template <>
constexpr int infty<int> = 1'000'000'000;
template <>
constexpr ll infty<ll> = ll(infty<int>) * infty<int> * 2;
template <>
constexpr u32 infty<u32> = infty<int>;
template <>
constexpr u64 infty<u64> = infty<ll>;
template <>
constexpr i128 infty<i128> = i128(infty<ll>) * infty<ll>;
template <>
constexpr double infty<double> = infty<ll>;
template <>
constexpr long double infty<long double> = infty<ll>;

using pi = pair<int, int>;
using pl = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
using vvi = vvc<int>;
using vvl = vvc<ll>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pqg = std::priority_queue<T, vector<T>, greater<T>>;
template <class T, class U>
using umap = unordered_map<T, U>;

// template <typename K>
// using tree = __gnu_pbds::tree<K, __gnu_pbds::null_type, std::less<>,
//                               __gnu_pbds::rb_tree_tag,
//                               __gnu_pbds::tree_order_statistics_node_update>;

#define vv(type, name, h, ...) \
    vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...)     \
    vector<vector<vector<type>>> name( \
        h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)         \
    vector<vector<vector<vector<type>>>> name( \
        a, vector<vector<vector<type>>>(       \
               b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

// FOR(a) :=  for (ll _ = 0; _ < (ll)a; ++_)
// FOR(i, a) := for (ll i = 0; i < (ll)a; ++i)
// FOR(i, a, b) := for (ll i = a; i < (ll)b; ++i)
// FOR(i, a, b, c) := for (ll i = a; i < (ll)b; i += (c))
// FOR_R(a) := for (ll i = (a) - 1; i >= 0; --i)
// FOR_R(i, a) := for (ll i = (a) - 1; i >= 0; --i)
// FOR_R(i, a, b) := for (ll i = (b) - 1; i >= (ll)a; --i)
#define FOR1(a) for (ll _ = 0; _ < (ll)a; ++_)
#define FOR2(i, a) for (ll i = 0; i < (ll)a; ++i)
#define FOR3(i, a, b) for (ll i = a; i < (ll)b; ++i)
#define FOR4(i, a, b, c) for (ll i = a; i < (ll)b; i += (c))
#define FOR1_R(a) for (ll i = (a) - 1; i >= 0; --i)
#define FOR2_R(i, a) for (ll i = (a) - 1; i >= 0; --i)
#define FOR3_R(i, a, b) for (ll i = (b) - 1; i >= (ll)a; --i)
#define overload4(a, b, c, d, e, ...) e
#define overload3(a, b, c, d, ...) d
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) overload3(__VA_ARGS__, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)

#define FOR_subset(t, s) \
    for (int t = (s); t >= 0; t = (t == 0 ? -1 : (t - 1) & (s)))
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()

int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
int popcnt_mod_2(int x) { return __builtin_parity(x); }
int popcnt_mod_2(u32 x) { return __builtin_parity(x); }
int popcnt_mod_2(ll x) { return __builtin_parityll(x); }
int popcnt_mod_2(u64 x) { return __builtin_parityll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T floor(T a, T b) {
    return a / b - (a % b && (a ^ b) < 0);
}
template <typename T>
T ceil(T x, T y) {
    return floor(x + y - 1, y);
}
template <typename T>
T bmod(T x, T y) {
    return x - y * floor(x, y);
}
template <typename T>
pair<T, T> divmod(T x, T y) {
    T q = floor(x, y);
    return {q, x - q * y};
}

template <typename T, typename U>
T POW(U x_, int n) {
    T x = x_;
    T ret = 1;
    while (n > 0) {
        if (n & 1) ret *= x;
        x *= x;
        n >>= 1;
    }
    return ret;
}

template <typename T, typename U>
T SUM(const vector<U> &A) {
    T sm = 0;
    for (auto &&a : A) sm += a;
    return sm;
}

#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) \
    sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()

template <class T, class S>
inline bool chmax(T &a, const S &b) {
    return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
    return (a > b ? a = b, 1 : 0);
}

// ? は -1
vc<int> s_to_vi(const string &S, char first_char) {
    vc<int> A(S.size());
    FOR(i, S.size()) { A[i] = (S[i] != '?' ? S[i] - first_char : -1); }
    return A;
}

template <typename T, typename U>
vector<T> cumsum(vector<U> &A, int off = 1) {
    int N = A.size();
    vector<T> B(N + 1);
    FOR(i, N) { B[i + 1] = B[i] + A[i]; }
    if (off == 0) B.erase(B.begin());
    return B;
}

template <typename T>
vector<int> argsort(const vector<T> &A) {
    vector<int> ids(A.size());
    iota(all(ids), 0);
    sort(all(ids),
         [&](int i, int j) { return (A[i] == A[j] ? i < j : A[i] < A[j]); });
    return ids;
}

// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
    vc<T> B(I.size());
    FOR(i, I.size()) B[i] = A[I[i]];
    return B;
}

template<class... T>
constexpr auto min(T... a){
    return min(initializer_list<common_type_t<T...>>{a...});
}
template<class... T>
constexpr auto max(T... a){
    return max(initializer_list<common_type_t<T...>>{a...});
}

void print(){
    cout << '\n';
}
template<class T>
void print(const T& a){
    cout << a << '\n';
}
template<class T, class... Ts>
void print(const T& a, const Ts&... b){
    cout << a;
    (cout << ... << (cout << ' ', b));
    cout << '\n';
}
template<class T>
void print(vector<T> &a){
    for (int i = 0; i < (int)a.size(); ++i) {
        cout << a[i] << " \n"[i == (int)a.size() - 1];
    }
}
template<class T>
void print(vector<T> &&a){
    for (int i = 0; i < (int)a.size(); ++i) {
        cout << a[i] << " \n"[i == (int)a.size() - 1];
    }
}
template<class T>
void print(vector<vector<T>> &a){
    for (int i = 0; i < (int)a.size(); ++i) {
        for (int j = 0; j < (int)a[i].size(); ++j) {
            cout << a[i][j] << " \n"[j == (int)a[i].size() - 1];
        }
    }
}
template<class T>
void print(vector<vector<T>> &&a){
    for (int i = 0; i < (int)a.size(); ++i) {
        for (int j = 0; j < (int)a[i].size(); ++j) {
            cout << a[i][j] << " \n"[j == (int)a[i].size() - 1];
        }
    }
}
void YESNO(bool b) { cout << (b ? "YES" : "NO") << endl; }
void YesNo(bool b) { cout << (b ? "Yes" : "No") << endl; }

#ifdef LOCAL
// https://zenn.dev/sassan/articles/19db660e4da0a4
#include "/Library/cpp-dump/dump.hpp"
#define dump(...) cpp_dump(__VA_ARGS__)
// CPP_DUMP_DEFINE_EXPORT_OBJECT(mint, val());
#else
#define dump(...)
#define CPP_DUMP_SET_OPTION(...)
#define CPP_DUMP_DEFINE_EXPORT_OBJECT(...)
#define CPP_DUMP_DEFINE_EXPORT_ENUM(...)
#define CPP_DUMP_DEFINE_DANGEROUS_EXPORT_OBJECT(...)
#endif


//----------------------------------------------------------------
// https://hackmd.io/@kcctdensan/rJ8CQtOki
// キーに素因数，値に何乗かを格納した連想配列を返すタイプ
template <class T>
map<T, T> prime_factorization(T N) {
    map<T, T> ans;
    T X = N;
    for (T i = 2; i * i <= N; i++) {
        if (X % i != 0) continue;
        if (X == 1) break;
        while (X % i == 0) {
            ans[i]++;
            X /= i;
        }
    }
    if (X != 1) ans[X]++;
    return ans;
}

bool solve() {
    ll M, A;
    cin >> M >> A;
    if (M == 0 && A == 0) {
        return false;
    }
    ll g = __gcd(M, A);
    M /= g;
    A /= g;
    auto fact = prime_factorization(g);
    ll ans = g;
    for (auto [p, _] : fact) {
        if (M % p == 0) continue;
        ans /= p;
        ans *= (p - 1);
    }
    print(ans);
    return true;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(20);
    CPP_DUMP_SET_OPTION(max_line_width, 80);
    CPP_DUMP_SET_OPTION(log_label_func, cpp_dump::log_label::filename());
    CPP_DUMP_SET_OPTION(enable_asterisk, true);
    while (solve()) {
    }
    return 0;
}
accuracy: 1
time_ms: 70
memory_kb: 3584
final_rank: 12

code_snippet: #include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

const int MOD = 998244353;
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());
#define mid (l+(r-l)/2)

using ll = long long;
using ld = long double;
using str = string;
using i128 = __int128;

using pii = pair<int,int>;
using pll = pair<ll,ll>;
using pd = pair<ld,ld>;
#define f first
#define s second
#define cf cout<<flush

template <class T> using V = vector<T>;
using vi = V<int>;
using vvi = V<vi>;
using vl = V<ll>;
using vvl = V<vl>;
using vd = V<ld>;
using vpi = V<pii>;
using vpl = V<pll>;

#define sz(x) int((x).size())
#define bg(x) begin(x)
#define all(x) bg(x), end(x)
#define sor(x) sort(all(x))
#define sorr(x) sort(all(x)),reverse(all(x))
#define uniq(x) sor(x), x.resize(unique(all(x))-x.begin())
#define pb push_back
#define ft front()
#define bk back()
#define chmi(x,y, ...) x = min(__VA_OPT__({) x,y __VA_OPT__(,)__VA_ARGS__ __VA_OPT__(}))
#define chma(x,y, ...) x = max(__VA_OPT__({) x,y __VA_OPT__(,)__VA_ARGS__ __VA_OPT__(}))
#define lwb(x,y) (int)(lower_bound(all(x),y)-x.begin())
#define upb(x,y) (int)(upper_bound(all(x),y)-x.begin())
#define compress(v) {auto _t=v;uniq(_t);for(auto &x:v)x=lwb(_t,x);}
#define in(x,y,n,m) (x>=0&&x<n&&y>=0&&y<m)
#define retu(args, ...) {ps(args __VA_OPT__(,)__VA_ARGS__);return ;}

#define For(i,a,b) for(int i = (a); i <= (b); i++)
#define F0r(i,a) for(int i = 0; i < (a); i++)
#define Rof(i,a,b) for(int i = (b); i >= (a); i--)
#define R0f(i,a) for(int i = (a)-1; i >= 0; i--)
#define rep(a) F0r(_,a)
#define each(a,x) for(auto &a:x)

const int dx[4]{1,0,-1,0},dy[4]{0,1,0,-1};
const int dx8[8]{1,1,0,-1,-1,-1,0,1},dy8[8]{0,1,1,1,0,-1,-1,-1};
template <class T> using pqg = priority_queue<T,vector<T>,greater<T>>;

constexpr int pct(int x){return __builtin_popcount(x);}
constexpr int pctll(long long x){return __builtin_popcountll(x);}
constexpr int bits(int x){return 31-__builtin_clz(x);}

#define SFINAE(x, ...)                                                         \
    template <class, class = void> struct x : std::false_type {};              \
    template <class T> struct x<T, std::void_t<__VA_ARGS__>> : std::true_type {}

SFINAE(DefaultI, decltype(std::cin >> std::declval<T &>()));
SFINAE(DefaultO, decltype(std::cout << std::declval<T &>()));
SFINAE(IsTuple, typename std::tuple_size<T>::type);
SFINAE(Iterable, decltype(std::begin(std::declval<T>())));

template <auto &is> struct Reader {
    template <class T> void Impl(T &t) {
        if constexpr (DefaultI<T>::value) is >> t;
        else if constexpr (Iterable<T>::value) {
            for (auto &x : t) Impl(x);
        } else if constexpr (IsTuple<T>::value) {
            std::apply([this](auto &...args) { (Impl(args), ...); }, t);
        } else static_assert(IsTuple<T>::value, "No matching type for read");
    }
    template <class... Ts> void read(Ts &...ts) { ((Impl(ts)), ...); }
};

template <class... Ts> void re(Ts &...ts) { Reader<cin>{}.read(ts...); }
#define def(t, args...)                                                        \
    t args;                                                                    \
    re(args);

template <auto &os, bool debug, bool print_nd> struct Writer {
    string comma() const { return debug ? "," : ""; }
    template <class T> constexpr char Space(const T &) const {
        return print_nd && (Iterable<T>::value or IsTuple<T>::value) ? '\n'
                                                                     : ' ';
    }
    template <class T> void Impl(T const &t) const {
        if constexpr (DefaultO<T>::value) os << t;
        else if constexpr (Iterable<T>::value) {
            if (debug) os << '{';
            int i = 0;
            for (auto &&x : t)
                ((i++) ? (os << comma() << Space(x), Impl(x)) : Impl(x));
            if (debug) os << '}';
        } else if constexpr (IsTuple<T>::value) {
            if (debug) os << '(';
            std::apply(
                [this](auto const &...args) {
                    int i = 0;
                    (((i++) ? (os << comma() << " ", Impl(args)) : Impl(args)),
                     ...);
                },
                t);
            if (debug) os << ')';
        } else static_assert(IsTuple<T>::value, "No matching type for print");
    }
    template <class T> void ImplWrapper(T const &t) const {
        if (debug) os << "\033[0;31m";
        Impl(t);
        if (debug) os << "\033[0m";
    }
    template <class... Ts> void print(Ts const &...ts) const {
        ((Impl(ts)), ...);
    }
    template <class F, class... Ts>
    void print_with_sep(const std::string &sep, F const &f,
                        Ts const &...ts) const {
        ImplWrapper(f), ((os << sep, ImplWrapper(ts)), ...), os << '\n';
    }
    void print_with_sep(const std::string &) const { os << '\n'; }
};

template <class... Ts> void pr(Ts const &...ts) {
    Writer<cout, false, true>{}.print(ts...);
}
template <class... Ts> void ps(Ts const &...ts) {
    Writer<cout, false, true>{}.print_with_sep(" ", ts...);
}

void setIn(str s) { freopen(s.c_str(), "r", stdin); }
void setOut(str s) { freopen(s.c_str(), "w", stdout); }
void setIO(str s = "") {
    cin.tie(0)->sync_with_stdio(0);
    cout << fixed << setprecision(12);
    if (sz(s)) setIn(s + ".in"), setOut(s + ".out");
}

//#include<atcoder/all>
//using namespace atcoder;
#define N 200005

//extgcd(a,b) return (x,y) that ax+by=gcd(a,b);

pair<long long,long long> extgcd(long long a,long long b){
    if(b==0)return make_pair(a>=0?1:-1,0);
    auto [y,x]=extgcd(b,a%b);
    y-=a/b*x;
    return make_pair(x,y);
}

// inverse mod of x by (mod)

long long inv(long long x,long long mod){
    assert(__gcd(x,mod)==1);
    auto [inv,_]=extgcd(x,mod);
    return (inv%mod+mod)%mod;
}

void solve(){
    def(ll,m,a);
    if(!m)exit(0);
    ll g=__gcd(m,a);
    ll c=inv(a/g,m/g);
    ll i=2,t=m;
    vl v;
    while(i*i<=t){
        if(t%i==0)v.pb(i);
        while(t%i==0){
            t/=i;
        }
        i++;
    }
    if(t!=1)v.pb(t);
    ll ans=0;
    // each(x,v)if(x!=1&&x%(m/g)==c)ans--;
    // For(i,1,m-1)if(i%(m/g)==c&&__gcd((ll)i,m)==1)ans++;
    
    F0r(i,1<<sz(v)){
        ll r=c,mod=m/g;
        int flag=false;
        F0r(j,sz(v))if(i>>j&1){
            ll x=v[j];
            if(mod%x==0&&r%x){
                flag=true;
                break;
            }
            auto [a,b]=extgcd(mod,x);
            mod*=x;
            r=(i128)b*x%mod*r%mod;
            if(r<0)r+=mod;            
        }
        
        if(flag)continue;
        
        ans+=(pct(i)%2?-1:1)*max((m-r+mod-1)/(mod),0ll);
        // ps(r,mod," ",v);
        // break;
    }
    
    ps(ans);
    
    return ;
}

int main(){
    setIO();
    int t=1;
    //re(t);
    while(true)solve();
    return 0;
}
accuracy: 1
time_ms: 80
memory_kb: 3584
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;

/// g:gcd(a, b), ax+by=g
struct EG {
  ll g, x, y;
};
EG ext_gcd(ll a, ll b) {
  if (b == 0) {
    if (a >= 0)
      return EG{a, 1, 0};
    else
      return EG{-a, -1, 0};
  } else {
    auto e = ext_gcd(b, a % b);
    return EG{e.g, e.y, e.x - a / b * e.y};
  }
}

bool solve(){
    ll m, a; cin >> m >> a;
    if(m == 0 && a == 0) return false;
    ll m2 = m;
    ll g = gcd(m, a);
    m /= g, a /= g;
    auto eg = ext_gcd(a, m);
    ll x = eg.x;
    x %= m; if(x < 0) x += m;
    vector<ll> primes;
    for(ll d = 2; d*d <= m2; d++) {
        if(m2 % d == 0) {
            primes.push_back(d);
            while(m2 % d == 0) m2 /= d;
        }
    }
    if(m2 > 1) primes.push_back(m2);
    ll np = ssize(primes);
    ll ans = 0;
    for(int s = 0; s < (1<<np); s++) {
        ll mod = 1;
        for(int j =0 ; j < np ;j++) {
            if(s>>j&1) mod *= primes[j];
        }
        // count -x = m'n (mod, 0<=n<g)
        ll gg = gcd(m, mod); // gcd(m',mod)
        if(x % gg != 0) continue;
        if(popcount((unsigned)s)%2==0) ans += g/(mod/gg);
        else ans -= g/(mod/gg);
    }
    cout << ans << '\n';
    return true;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    while(solve());
}
accuracy: 1
time_ms: 80
memory_kb: 3456
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define ALL(v) (v).begin(), (v).end()
using ll = long long;
#define rep(i,l,r) for(ll i=(l);i<(r); i++)

template<size_t maxN>
struct Sieve {
    std::vector<int> is_prime;
    std::vector<int> prime;
    std::vector<int> minfac;
    Sieve() : is_prime(maxN, 1), prime(), minfac(maxN, -1) {
        is_prime[0] = is_prime[1] = 0;
        std::iota(minfac.begin(), minfac.end(), 0);
        for (size_t i = 4; i <= maxN; i+=2) {
            is_prime[i] = 0;
            minfac[i] = 2;
        }
        for (size_t i = 3; i*i <= maxN; i+=2) {
            if (!is_prime[i]) continue;
            minfac[i] = i;
            for (size_t j = i*i; j <= maxN; j+=2*i) {
                is_prime[j] = 0;
                if (minfac[j] > i) minfac[j] = i;
            }
        }
        for (size_t i = 2; i <= maxN; i++) {
            if (is_prime[i]) prime.emplace_back(i);
        }
    }
    std::vector<std::pair<ll,ll>> factorize(ll N) {
        std::vector<std::pair<ll,ll>> res;
        while (N != 1) {
            ll bs = minfac[N], exp = 0;
            while (minfac[N] == bs) {
                N /= bs;
                exp++;
            }
            res.emplace_back(bs, exp);
        }
        return res;
    }
    std::vector<int> divisors(int N) {
        std::vector<int> res{1};
        for (auto [bs, exp] : factorize(N)) {
            int len = res.size();
            for (int i = 0; i < len; i++) {
                int x = 1;
                for (int j = 0; j < exp; j++) {
                    x *= bs;
                    res.emplace_back(res[i] * x);
                }
            }
        }
        return res;
    }
};



auto ES = Sieve<1'000'001>();

int main() {
    vector<ll> es(0);
    bool n[1000001];
    rep(i,2,1000001){
        n[i]=true;
    }
    rep(i,2,1001){
        if(n[i]){
            rep(j,2,1000001/i+1){
              n[i*j]=false;
            }
        }
    }
    rep(i,2,1000001)if(n[i])es.push_back(i);//eratos clear
    while(true){
    ll m,a;cin>>m>>a;
    if(m==0)break;
    ll g=gcd(m,a);
    ll l=m/g;
    ll ans=g;
    vector<ll> v,t;
    for(auto x: es){
        if(g%x==0){
            v.push_back(x);
            while(g%x==0)g/=x;
        }
    }
    if(g!=1)v.push_back(g);
    for (auto vv: v) {
        //cerr << "v = " << vv << endl;
    }
    //cerr << "l = "<< l << endl;
    for(auto x: es){
        if(l%x==0){
            t.push_back(x);
            while(l%x==0)l/=x;
        }
    }
    if(l!=1)t.push_back(l);
    for (auto vv: t) {
        //cerr << "t = " << vv << endl;
    }
    //eratostenes tukaitai s
    set<ll>s;
    for(auto &x: v) {
        s.insert(x);
    }
    for(auto &x: t){
        if(s.count(x)){
            s.erase(x);
        }
    }

    for(auto p: s){
        ans/=p;ans*=(p-1);
    }
    cout<<ans<<endl;
    }
}
accuracy: 1
time_ms: 160
memory_kb: 13528
final_rank: 20

code_snippet: #include <algorithm>
#include <array>
#include <bit>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <ranges>
#include <regex>
#include <set>
#include <span>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// #include <atcoder/dsu>

#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
#define all(a) a.begin(), a.end()
using namespace std;

template <class T> inline bool chmin(T &a, T b) {
	if (a > b) {
		a = b;
		return true;
	}
	return false;
}
template <class T> inline bool chmax(T &a, T b) {
	if (a < b) {
		a = b;
		return true;
	}
	return false;
}

template <class T1, class T2>
std::ostream &operator<<(std::ostream &out, const pair<T1, T2> &A) {
	cout << "{" << A.first << "," << A.second << "}";
	return out;
}

template <class T1, class T2>
std::ostream &operator<<(std::ostream &out, const map<T1, T2> &M) {
	for (const auto &A : M) {
		cout << "{" << A.first << "," << A.second << "}";
	}
	return out;
}

template <class T1>
std::ostream &operator<<(std::ostream &out, const set<T1> &M) {
	cout << "{";
	for (const auto &A : M) {
		cout << A << ", ";
	}
	cout << "}" << endl;
	return out;
}

template <class T1>
std::ostream &operator<<(std::ostream &out, const multiset<T1> &M) {
	cout << "{";
	for (const auto &A : M) {
		cout << A << ", ";
	}
	cout << "}" << endl;
	return out;
}

template <class T>
std::ostream &operator<<(std::ostream &out, const vector<T> &A) {
	for (const T &a : A) {
		cout << a << " ";
	}
	return out;
}

void print() { cout << endl; }

template <typename Head, typename... Tail> void print(Head H, Tail... T) {
	cout << H << " ";
	print(T...);
}

template <class T> std::istream &operator>>(std::istream &in, vector<T> &A) {
	for (T &a : A) {
		std::cin >> a;
	}
	return in;
}

using ll = long long;
// using mint = modint1000000007;
// using PII = pair<int, int>;
// using PLL = pair<ll, ll>;
// using Graph = vector<vector<int>>;
constexpr int INF = numeric_limits<int>::max() / 2;
constexpr ll LINF = numeric_limits<ll>::max() / 2;

// ランレングス圧縮
// イテレータを受け取る
// verify: https://atcoder.jp/contests/abc380/submissions/60002447
template <typename T, typename Iterator>
vector<pair<T, int>> RLE(Iterator begin, Iterator end) {
	vector<pair<T, int>> res;
	for (auto itr = begin; itr != end; ++itr) {
		if (res.empty() || res.back().first != *itr) {
			res.emplace_back(*itr, 1);
		} else {
			res.back().second++;
		}
	}
	return res;
}

// 座標圧縮
// unordered_mapが使えない場合はmapに変更しよう
// https://atcoder.jp/contests/abc213/submissions/60002695
template <typename T> unordered_map<T, int> compress(vector<T> &X) {
	auto tmp = X;
	ranges::sort(tmp);
	tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());
	unordered_map<T, int> res;
	for (int i = 0; i < (int)tmp.size(); i++) {
		res[tmp[i]] = i;
	}
	return res;
}

ll extGCD(ll a, ll b, ll &x, ll &y) {
	if (b == 0) {
		x = 1;
		y = 0;
		return a;
	}
	ll d = extGCD(b, a % b, y, x);
	y -= a / b * x;
	return d;
}

ll inverse(ll a, ll n) {
	assert(gcd(a, n) == 1);
	ll x, y;
	extGCD(a, n, x, y);
	assert((x + n) >= 0);
	return (x + n) % n;
}

// 素因数分解
vector<pair<ll, ll>> prime_factor(ll n) {
	vector<pair<ll, ll>> res;
	for (ll i = 2; i * i <= n; i++) {
		if (n % i != 0)
			continue;
		res.emplace_back(i, 0);
		while (n % i == 0) {
			n /= i;
			res.back().second++;
		}
	}
	if (n != 1)
		res.emplace_back(n, 1);
	return res;
}

bool solve() {
	// ここからスタート
	ll M, A;
	cin >> M >> A;
	/*

	M = rand() % 10000000 + 2;
	A = rand() % (100 - 1) + 1;
	*/
	if (M == 0)
		return false;
	ll g = gcd(M, A);
	ll M1 = M / g, A1 = A / g;
	ll a = inverse(A1, M1);
	ll b = M1;
	// a+bk
	auto fac = prime_factor(g);
	vector<ll> prime;
	for (auto [p, e] : fac) {
		prime.push_back(p);
	}

	ll ans = (M - a - 1) / b + 1;
	ll kmax = ans;
	int N = prime.size();
	for (int i = 1; i < (1 << N); i++) {
		ll mod = 1;
		rep(k, N) {
			if ((1 << k) & i) {
				mod *= prime[k];
			}
		}
		// 0 <= k <= kmax かつ
		ll bmod = b % mod;
		ll amod = a % mod;
		amod = (mod - amod) % mod;
		ll cnt = 0;
		if (bmod != 1) {
			if (gcd(mod, bmod) == 1) {
				// amod = (amod * inverse(bmod, mod)) % mod;
				__int128 a128 = amod;
				__int128 b128 = inverse(bmod, mod);
				__int128 m128 = mod;
				amod = (a128 * b128) % m128;
				bmod = 1;
				cnt = (M - a - b * amod - 1) / (b * mod) + 1;
			} else {
				if (amod == 0) {
					cnt = kmax;
				} else {
					cnt = 0;
				}
			}
		} else {
			cnt = (M - a - b * amod - 1) / (b * mod) + 1;
		}
		// bmod k = amod (mod modで)
		ans = ans + (cnt) * ((popcount((unsigned int)(i)) % 2 == 0) ? 1 : -1);
	}

	/*
	for (int x = 1; x < M; x++) {
		if (gcd(M, x) == 1 && (A * x) % M == gcd(M, A)) {
			cnt++;
		}
	}
		*/
	// cout << "(M,A) " << M << " " << A << endl;
	cout << ans << endl;
	// cout << "ぐちょく" << cnt << endl;
	// assert(ans == cnt);
	return true;
}

int main(void) {
	std::cin.tie(0)->sync_with_stdio(0);
	while (solve())
		;
}
accuracy: 1
time_ms: 20
memory_kb: 3456
final_rank: 3

code_snippet: #include <bits/stdc++.h>
    using namespace std;
    
    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; }
    #define rep(i,n) for (int i = 0; i < (n); ++i)

    typedef long long ll;
    typedef unsigned long long ull;
    using P=pair<ll,ll>;
    using tp=tuple<ll,ll,ll>;
    const int INF=1001001001;
    const ll INFL=1e18;
    const int mod=998244353;

// 拡張 Euclid の互除法
// ap + bq = gcd(a, b) となる (p, q) を求め、d = gcd(a, b) をリターンします
long long extGcd(long long a, long long b, long long &p, long long &q) {  
	if (b == 0) { p = 1; q = 0; return a; }  
	long long d = extGcd(b, a%b, q, p);  
	q -= a/b * p;  
	return d;  
}

const int MAX_N=200005;

ll euler_phi(ll n){
	ll res=n;
	for(ll i=2;i*i<=n;i++){
		if(n%i==0){
			res=res/i*(i-1);
			while(n%i==0){
				n/=i;
			}
		}
	}
	if(n!=1)res=res/n*(n-1);
	return res;
}

int euler[MAX_N];
void euler_phi2(){
	for(int i=0;i<MAX_N;i++)euler[i]=i;
	for(int i=2;i<MAX_N;i++){
		if(euler[i]==i){
			for(int j=i;j<MAX_N;j+=i){
				euler[j]=euler[j]/i*(i-1);
			}
		}
	}
}

vector<pair<ll,ll>>prime_factorize(ll N) {
  vector<pair<ll,ll>>res;
  for (ll i= 2; i*i<=N;i++) {
	if (N%i!=0){continue;}
	ll cnt=0; 
	while(N%i==0){
	  cnt++;
	  N/=i;
	}
	res.push_back({i, cnt});
  }
  if(N!=1){res.push_back({N, 1});}
  return res;
}

    bool solve(){
		ll m,a;
		cin>>m>>a;
		if(m==0&&a==0)return false;

		ll x,y;
		ll g=extGcd(a,m,x,y);
		ll mm=m/g,mmm=m;
		auto p=prime_factorize(mm);
		for(auto [pr,c]:p){
			while(mmm%pr==0){
				mmm/=pr;
			}
		}
		ll ans=euler_phi(mmm)*(g/mmm);
        cout<<ans<<endl;
		return true;
    }

    int main(){
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);

		while(1){
			if(!solve()){break;}
		}
		
        return 0;
    }
accuracy: 1
time_ms: 80
memory_kb: 3456
final_rank: 9

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double x) {
    wt_real(x);
}

template <class T, class U> void wt(const pair<T, U> val) {
    wt(val.first);
    wt(' ');
    wt(val.second);
}
template <size_t N = 0, typename T> void wt_tuple(const T t) {
    if constexpr (N < std::tuple_size<T>::value) {
        if constexpr (N > 0) {
            wt(' ');
        }
        const auto x = std::get<N>(t);
        wt(x);
        wt_tuple<N + 1>(t);
    }
}
template <class... T> void wt(tuple<T...> tpl) {
    wt_tuple(tpl);
}
template <class T, size_t S> void wt(const array<T, S> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}
template <class T> void wt(const vector<T> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}

void print() {
    wt('\n');
}
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail) {
    wt(head);
    if (sizeof...(Tail))
        wt(' ');
    print(forward<Tail>(tail)...);
}
void __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

int main() {
while(1) {
    long long M, A;
    cin >> M >> A;
    if (M == 0 && A == 0) return 0;
    long long G = gcd(A,M);
    long long N = M;
    while(1) {
        if (gcd(M/G,N) == 1) break;
        N /= gcd(M/G,N);
    }
    long long L = N;
    ll ANS = N;
    for (ll i = 2; i * i <= N; i++) {
        if (L % i == 0) {
            ANS -= ANS / i;
            while(L % i == 0) {
                L /= i;
            }
        }
    }
    if (L >=  2) {
        ANS -= ANS / L;
    }
    cout << ANS * (G / N) << endl;
}
}
accuracy: 1
time_ms: 160
memory_kb: 3492
final_rank: 15

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef vector<vvb> vvvb;
typedef vector<vvvb> vvvvb;
typedef pair<ll,ll> pi;
typedef pair<ll,pi> ppi;
#define FOR(i,l,r) for(ll i=l;i<r;i++)
#define REP(i,n) FOR(i,0,n)
#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)
#define RREP(i,n) RFOR(i,0,n)
#define sz(A) (ll)(A.size())
#define ALL(A) A.begin(),A.end()
#define LB(A,x) (ll)(lower_bound(ALL(A),x)-A.begin())
#define UB(A,x) (ll)(upper_bound(ALL(A),x)-A.begin())
#define COU(A,x) (UB(A,x)-LB(A,x))
#define F first
#define S second
template<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;
template<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.F<<" "<<p.S;return os;}
template<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.F>>p.S;return is;}
template<typename T>ostream&operator<<(ostream&os,vector<T>&v){REP(i,sz(v))os<<v[i]<<(i+1!=sz(v)?" ":"");return os;}
template<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}
template<class T>bool chmax(T&a,T b){if(a<b){a=b;return 1;}return 0;}
template<class T>bool chmin(T&a,T b){if(b<a){a=b;return 1;}return 0;}
const ll mod=998244353;
template<const long long int mod=998244353>
struct modint{
  using mint=modint<mod>;
  long long int x;
  modint(long long int _x=0):x(_x%mod){if(x<0)x+=mod;}
  long long int val(){return x;}
  mint&operator=(const mint&a){x=a.x;return *this;}
  mint&operator+=(const mint&a){x+=a.x;if(x>=mod)x-=mod;return *this;}
  mint&operator-=(const mint&a){x-=a.x;if(x<0)x+=mod;return *this;}
  mint&operator*=(const mint&a){x*=a.x;x%=mod;return *this;}
  friend mint operator+(const mint&a,const mint&b){return mint(a)+=b;}
  friend mint operator-(const mint&a,const mint&b){return mint(a)-=b;}
  friend mint operator*(const mint&a,const mint&b){return mint(a)*=b;}
  mint operator-()const{return mint(0)-*this;}
  mint pow(long long int n){
    if(!n)return 1;
    mint a=1;
    mint _x=x;
    while(n){
      if(n&1)a*=_x;
      _x=_x*_x;n>>=1;
    }
    return a;
  }
  mint inv(){return pow(mod-2);}
  mint&operator/=(mint&a){return *this*=a.inv();}
  friend mint operator/(const mint&a,mint b){return mint(a)/=b;}
};
using mint=modint<998244353>;

#include <algorithm>
#include <cassert>
#include <tuple>
#include <vector>


#include <utility>

#ifdef _MSC_VER
#include <intrin.h>
#endif

namespace atcoder {

namespace internal {

constexpr long long safe_mod(long long x, long long m) {
    x %= m;
    if (x < 0) x += m;
    return x;
}

struct barrett {
    unsigned int _m;
    unsigned long long im;

    explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}

    unsigned int umod() const { return _m; }

    unsigned int mul(unsigned int a, unsigned int b) const {

        unsigned long long z = a;
        z *= b;
#ifdef _MSC_VER
        unsigned long long x;
        _umul128(z, im, &x);
#else
        unsigned long long x =
            (unsigned long long)(((unsigned __int128)(z)*im) >> 64);
#endif
        unsigned long long y = x * _m;
        return (unsigned int)(z - y + (z < y ? _m : 0));
    }
};

constexpr long long pow_mod_constexpr(long long x, long long n, int m) {
    if (m == 1) return 0;
    unsigned int _m = (unsigned int)(m);
    unsigned long long r = 1;
    unsigned long long y = safe_mod(x, m);
    while (n) {
        if (n & 1) r = (r * y) % _m;
        y = (y * y) % _m;
        n >>= 1;
    }
    return r;
}

constexpr bool is_prime_constexpr(int n) {
    if (n <= 1) return false;
    if (n == 2 || n == 7 || n == 61) return true;
    if (n % 2 == 0) return false;
    long long d = n - 1;
    while (d % 2 == 0) d /= 2;
    constexpr long long bases[3] = {2, 7, 61};
    for (long long a : bases) {
        long long t = d;
        long long y = pow_mod_constexpr(a, t, n);
        while (t != n - 1 && y != 1 && y != n - 1) {
            y = y * y % n;
            t <<= 1;
        }
        if (y != n - 1 && t % 2 == 0) {
            return false;
        }
    }
    return true;
}
template <int n> constexpr bool is_prime = is_prime_constexpr(n);

constexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {
    a = safe_mod(a, b);
    if (a == 0) return {b, 0};

    long long s = b, t = a;
    long long m0 = 0, m1 = 1;

    while (t) {
        long long u = s / t;
        s -= t * u;
        m0 -= m1 * u;  // |m1 * u| <= |m1| * s <= b


        auto tmp = s;
        s = t;
        t = tmp;
        tmp = m0;
        m0 = m1;
        m1 = tmp;
    }
    if (m0 < 0) m0 += b / s;
    return {s, m0};
}

constexpr int primitive_root_constexpr(int m) {
    if (m == 2) return 1;
    if (m == 167772161) return 3;
    if (m == 469762049) return 3;
    if (m == 754974721) return 11;
    if (m == 998244353) return 3;
    int divs[20] = {};
    divs[0] = 2;
    int cnt = 1;
    int x = (m - 1) / 2;
    while (x % 2 == 0) x /= 2;
    for (int i = 3; (long long)(i)*i <= x; i += 2) {
        if (x % i == 0) {
            divs[cnt++] = i;
            while (x % i == 0) {
                x /= i;
            }
        }
    }
    if (x > 1) {
        divs[cnt++] = x;
    }
    for (int g = 2;; g++) {
        bool ok = true;
        for (int i = 0; i < cnt; i++) {
            if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {
                ok = false;
                break;
            }
        }
        if (ok) return g;
    }
}
template <int m> constexpr int primitive_root = primitive_root_constexpr(m);

unsigned long long floor_sum_unsigned(unsigned long long n,
                                      unsigned long long m,
                                      unsigned long long a,
                                      unsigned long long b) {
    unsigned long long ans = 0;
    while (true) {
        if (a >= m) {
            ans += n * (n - 1) / 2 * (a / m);
            a %= m;
        }
        if (b >= m) {
            ans += n * (b / m);
            b %= m;
        }

        unsigned long long y_max = a * n + b;
        if (y_max < m) break;
        n = (unsigned long long)(y_max / m);
        b = (unsigned long long)(y_max % m);
        std::swap(m, a);
    }
    return ans;
}

}  // namespace internal

}  // namespace atcoder


namespace atcoder {

long long pow_mod(long long x, long long n, int m) {
    assert(0 <= n && 1 <= m);
    if (m == 1) return 0;
    internal::barrett bt((unsigned int)(m));
    unsigned int r = 1, y = (unsigned int)(internal::safe_mod(x, m));
    while (n) {
        if (n & 1) r = bt.mul(r, y);
        y = bt.mul(y, y);
        n >>= 1;
    }
    return r;
}

long long inv_mod(long long x, long long m) {
    assert(1 <= m);
    auto z = internal::inv_gcd(x, m);
    assert(z.first == 1);
    return z.second;
}

std::pair<long long, long long> crt(const std::vector<long long>& r,
                                    const std::vector<long long>& m) {
    assert(r.size() == m.size());
    int n = int(r.size());
    long long r0 = 0, m0 = 1;
    for (int i = 0; i < n; i++) {
        assert(1 <= m[i]);
        long long r1 = internal::safe_mod(r[i], m[i]), m1 = m[i];
        if (m0 < m1) {
            std::swap(r0, r1);
            std::swap(m0, m1);
        }
        if (m0 % m1 == 0) {
            if (r0 % m1 != r1) return {0, 0};
            continue;
        }


        long long g, im;
        std::tie(g, im) = internal::inv_gcd(m0, m1);

        long long u1 = (m1 / g);
        if ((r1 - r0) % g) return {0, 0};

        long long x = (r1 - r0) / g % u1 * im % u1;

        r0 += x * m0;
        m0 *= u1;  // -> lcm(m0, m1)
        if (r0 < 0) r0 += m0;
    }
    return {r0, m0};
}

long long floor_sum(long long n, long long m, long long a, long long b) {
    assert(0 <= n && n < (1LL << 32));
    assert(1 <= m && m < (1LL << 32));
    unsigned long long ans = 0;
    if (a < 0) {
        unsigned long long a2 = internal::safe_mod(a, m);
        ans -= 1ULL * n * (n - 1) / 2 * ((a2 - a) / m);
        a = a2;
    }
    if (b < 0) {
        unsigned long long b2 = internal::safe_mod(b, m);
        ans -= 1ULL * n * ((b2 - b) / m);
        b = b2;
    }
    return ans + internal::floor_sum_unsigned(n, m, a, b);
}

}  // namespace atcoder

using namespace atcoder;
int main(){
    while(1){
        ll M,A;cin>>M>>A;
        if(!M)return 0;
        ll g=__gcd(A,M);
        ll m=M/g;
        ll ans=g;
        ll d=2;
        while(d*d<=g){
            if(g%d==0){
                if(m%d)ans-=ans/d;
            }
            while(g%d==0)g/=d;
            d++;
        }
        if(g>1&&m%g)ans-=ans/g;
        cout<<ans<<endl;
    }
    return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 3324
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define ALL(v) v.begin(),v.end()
#define dbg(x) cerr << #x << ": " << x << endl;
template<class F, class S>
ostream& operator << (ostream& os, pair<F,S> p) {
    return os << '(' << p.first << ',' << p.second << ')';
}
template<class Iter>
void print(Iter beg, Iter end) {
    for (Iter itr = beg; itr != end; ++itr) {
        cerr << *itr << ' ';
    }
    cerr << endl;
}
// 返り値: a と b の最大公約数
// ax + by = gcd(a, b) を満たす (x, y) が格納される
long long extGCD(long long a, long long b, long long &x, long long &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    long long d = extGCD(b, a%b, y, x);
    y -= a/b * x;
    return d;
}

ll solve() {
    long long m, a;
    cin >> m >> a;
    if (a + m == 0) exit(0);
    long long g = gcd(m, a);
    ll b = a/g;
    ll c = m/g;
    vector<ll> p;
    {
    ll tmp = m;
    for (ll i = 2; i * i <= tmp; ++i)
    {
        int cnt = 0;
        while (tmp % i == 0)
        {
            ++cnt;
            tmp /= i;
        }
        if (cnt) p.push_back(i);
    }
    if (tmp > 1) p.push_back(tmp);
    }
    ll x,y;
    ll d = extGCD(b,-c,x,y);
    x %= c;
    ll xma = m / c * c + x;
    if (xma >= m) xma -= c;
    ll kmax = (xma - x) / c;

    int siz = p.size();
    ll ans = 0;
    for (int i = 0; i < 1 << siz; ++i)
    {
        ll l = 1, sum = 0;
        for (int j = 0; j < siz; ++j)
        {
            if (i & (1 << j))
            {
                l *= p[j];
            }
        }
        
        ll tx, ty;
        ll tg = extGCD(l, -c, tx, ty);
        if (x % tg != 0) continue;
        ll tmp = lcm(l, c);
        ll dtk = (tmp / c);
        ll mitk = (ty % dtk + dtk) % dtk;
        ll matk = (kmax / dtk * dtk + mitk);
        if (matk > kmax) matk -= dtk;
        sum = max(0LL, (matk - mitk) / dtk + 1);

        ans += (__builtin_popcount(i) % 2 ? -1 : 1) * sum;
    }
    return ans;
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cout << fixed << setprecision(20); cerr << fixed << setprecision(6);
    while (true) {
        // solve();
        cout << solve() << '\n';
        // cout << (solve() ? "Yes" : "No") << '\n';
    }
}
accuracy: 1
time_ms: 230
memory_kb: 3384
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 1e9 + 10;
const ll INFL = 4e18;

/*
    一旦2を無視して1のみを考えてみる。

    [$ Ax\equiv \gcd(A,M) \mod{M}]を満たす[$ x]は、不定方程式[$ Ax+My=\gcd(A,M)]を拡張ユークリッドの互助法で解くことで簡単に求められる。

    ここで、[$ G=\gcd(A,M), A=A'G, M=M'G]とおくと、

    [$ Ax+My=G]
    [$ A'x+M'y=1]

    よって、[** 解[$ x]と[$ M']は互いに素であり、さらに、[$ x=x_0+M't]の形で表される。 ]
    これを元の方程式に入れると[$ A(x_0+\frac{M}{G}t)\equiv G\mod{M}]の形で表され、[$ 0\le t< G]である。
    つまり、元の問題で求める[$ x]は全て[$ x=x_0+\frac{M}{G}t\,(0\le t< G)]の形で表されることがわかった。

    ここまでの議論により、この問題は[$ x=x_0+\frac{M}{G}t]が[$ M]と互いに素になるような[$ t(0\le t< G)]の個数を求める問題と言い換えることができた。

    さて、先ほどの議論より、[$ x]は[$ M']とは互いに素であることが保証される。よって、[$ M]から[$ M']の素因数を除いた[$ M'']に対して検討する。

    [** [$ x=x_0+\frac{M}{G}t\mod{M''}]とすると、[$ \gcd(M',M'')=1]より、[$ x]は[$ 0\le x<M'']の全ての整数を取れる。]

    よって、[$ 0\le x<M'']に対しては、[$ M'']と互いに素な整数は全て[$ x]としてカウントでき、この個数は[$ \phi(M'')]である。
*/

ll euler_phi(ll n) {
    vector<ll> divs;
    for (ll i = 1; i * i <= n; i++) {
        if (n % i == 0) {
            divs.push_back(i);
            if (i * i != n) {
                divs.push_back(n / i);
            }
        }
    }
    sort(divs.begin(), divs.end());
    ll m = divs.size();
    vector<ll> dp(m);
    for (int i = m - 1; i >= 0; i--) {
        dp[i] = n / divs[i];
        for (int j = i + 1; j < m; j++) {
            if (divs[j] % divs[i] == 0) {
                dp[i] -= dp[j];
            }
        }
    }
    return dp[0];
}

int main() {
    while (true) {
        ll M, A;
        cin >> M >> A;
        if (M == 0) {
            break;
        }

        ll G = gcd(A, M);
        ll M2 = M / G;
        ll M3 = M;

        while (gcd(M2, M3) > 1) {
            M3 /= gcd(M2, M3);
        }

        cout << euler_phi(M3) * (G / M3) << endl;
    }
}
accuracy: 1
time_ms: 170
memory_kb: 3208
final_rank: 7

code_snippet: #ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif
// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <unordered_set>

#endif
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
template <class T, class U>
inline bool chmax(T &a, U b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T, class U>
inline bool chmin(T &a, U b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
constexpr int INF = 1001001001;
constexpr int64_t llINF = 3000000000000000000;
const double pi = acos(-1);
struct linear_sieve {
    vector<int> least_factor, prime_list;
    linear_sieve(int n) : least_factor(n + 1, 0) {
        for (int i = 2; i <= n; i++) {
            if (least_factor[i] == 0) {
                least_factor[i] = i;
                prime_list.push_back(i);
            }
            for (int p : prime_list) {
                if (ll(i) * p > n || p > least_factor[i]) break;
                least_factor[i * p] = p;
            }
        }
    }
};

ll extgcd(ll a, ll b, ll &x, ll &y) {
    // ax+by=gcd(|a|,|b|)
    if (a < 0 || b < 0) {
        ll d = extgcd(abs(a), abs(b), x, y);
        if (a < 0) x = -x;
        if (b < 0) y = -y;
        return d;
    }
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
ll modpow(ll a, ll b, ll m) {
    a %= m;
    ll res = 1 % m;
    while (b) {
        if (b & 1) {
            res *= a;
            res %= m;
        }
        a *= a;
        a %= m;
        b >>= 1;
    }
    return res;
}
ll modinv(ll x, ll modulo) {
    ll a = x, b = modulo, u = 1, v = 0, t;
    while (b > 0) {
        t = a / b;
        swap(a -= t * b, b);
        swap(u -= t * v, v);
    }
    return (u >= 0 ? u % modulo : (modulo - (-u) % modulo) % modulo);
}
template <int modulo>
struct modint {
    int x;
    modint() : x(0) {}
    modint(int64_t y) : x(y >= 0 ? y % modulo : (modulo - (-y) % modulo) % modulo) {}
    modint &operator+=(const modint &p) {
        if ((x += p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint &operator-=(const modint &p) {
        if ((x += modulo - p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint &operator*=(const modint &p) {
        x = (int)(1LL * x * p.x % modulo);
        return *this;
    }
    modint &operator/=(const modint &p) {
        *this *= p.inv();
        return *this;
    }
    modint operator-() const { return modint(-x); }
    modint operator+(const modint &p) const { return modint(*this) += p; }
    modint operator-(const modint &p) const { return modint(*this) -= p; }
    modint operator*(const modint &p) const { return modint(*this) *= p; }
    modint operator/(const modint &p) const { return modint(*this) /= p; }
    bool operator==(const modint &p) const { return x == p.x; }
    bool operator!=(const modint &p) const { return x != p.x; }
    modint inv() const {
        int a = x, b = modulo, u = 1, v = 0, t;
        while (b > 0) {
            t = a / b;
            swap(a -= t * b, b);
            swap(u -= t * v, v);
        }
        return modint(u);
    }
    modint pow(int64_t n) const {
        modint ret(1), mul(x);
        while (n > 0) {
            if (n & 1) ret *= mul;
            mul *= mul;
            n >>= 1;
        }
        return ret;
    }
    friend ostream &operator<<(ostream &os, const modint &p) { return os << p.x; }
    friend istream &operator>>(istream &is, modint &a) {
        int64_t t;
        is >> t;
        a = modint<modulo>(t);
        return (is);
    }
    int val() const { return x; }
    static constexpr int mod() { return modulo; }
    static constexpr int half() { return (modulo + 1) >> 1; }
};
template <typename T>
struct Binomial {
    vector<T> inv, fact, factinv;
    Binomial(int n) {
        inv.resize(n + 1);
        fact.resize(n + 1);
        factinv.resize(n + 1);
        inv[0] = fact[0] = factinv[0] = 1;
        for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
        factinv[n] = fact[n].inv();
        inv[n] = fact[n - 1] * factinv[n];
        for (int i = n - 1; i >= 1; i--) {
            factinv[i] = factinv[i + 1] * (i + 1);
            inv[i] = fact[i - 1] * factinv[i];
        }
    }
    T C(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r] * factinv[r];
    }
    T P(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r];
    }
    T H(int n, int r) {
        if (n == 0 && r == 0) return 1;
        if (n < 0 || r < 0) return 0;
        return r == 0 ? 1 : C(n + r - 1, r);
    }
};
template <class T>
struct Matrix {
    int n;
    vector<vector<T>> m;
    Matrix() : Matrix(0) {}
    Matrix(int x) : Matrix(vector<vector<T>>(x, vector<T>(x, 0))) {}
    Matrix(const vector<vector<T>> &a) {
        n = a.size();
        m = a;
    }
    vector<T> &operator[](int i) { return m[i]; }
    const vector<T> &operator[](int i) const { return m[i]; }
    static Matrix identity(int x) {
        Matrix res(x);
        for (int i = 0; i < x; i++) res[i][i] = 1;
        return res;
    }
    Matrix operator+(const Matrix &a) const {
        Matrix x = (*this);
        return x += a;
    }
    Matrix operator*(const Matrix &a) const {
        Matrix x = (*this);
        return x *= a;
    }
    Matrix &operator+=(const Matrix &a) {
        Matrix res(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                res[i][j] = m[i][j] + a[i][j];
            }
        }
        m = res.m;
        return *this;
    }
    Matrix &operator*=(const Matrix &a) {
        Matrix res(n);
        for (int i = 0; i < n; i++) {
            for (int k = 0; k < n; k++) {
                for (int j = 0; j < n; j++) {
                    res[i][j] += m[i][k] * a[k][j];
                }
            }
        }
        m = res.m;
        return *this;
    }
    Matrix pow(ll b) const {
        Matrix x = *this, res = identity(n);
        while (b) {
            if (b & 1) {
                res *= x;
            }
            x *= x;
            b >>= 1;
        }
        return res;
    }
};
struct UnionFind {
    vector<int> par, siz, es;
    UnionFind(int x) {
        par.resize(x);
        siz.resize(x);
        es.resize(x);
        for (int i = 0; i < x; i++) {
            par[i] = i;
            siz[i] = 1;
            es[i] = 0;
        }
    }
    int find(int x) {
        if (par[x] == x) return x;
        return par[x] = find(par[x]);
    }
    bool unite(int x, int y) {
        x = find(x), y = find(y);
        if (x == y) {
            es[x]++;
            return false;
        }
        if (siz[x] < siz[y]) swap(x, y);
        par[y] = x;
        siz[x] += siz[y];
        es[x] += es[y] + 1;
        return true;
    }
    bool same(int x, int y) { return find(x) == find(y); }
    int size(int x) { return siz[find(x)]; }
    int edges(int x) { return es[find(x)]; }
};
template <class S, S (*op)(S, S), S (*e)()>
struct segtree {
    int siz = 1;
    vector<S> dat;
    segtree(int n) : segtree(vector<S>(n, e())) {}
    segtree(const vector<S> &a) {
        while (siz < a.size()) siz <<= 1;
        dat = vector<S>(siz << 1, e());
        for (int i = 0; i < a.size(); i++) dat[siz + i] = a[i];
        for (int i = siz - 1; i >= 1; i--) dat[i] = op(dat[2 * i], dat[2 * i + 1]);
    }
    void set(int p, S x) {
        p += siz;
        dat[p] = x;
        while (p > 0) {
            p >>= 1;
            dat[p] = op(dat[2 * p], dat[2 * p + 1]);
        }
    }
    void add(int p, S x) { set(p, get(p) + x); }
    S get(int p) { return dat[p + siz]; }
    S prod(int l, int r) {
        S vl = e(), vr = e();
        l += siz, r += siz;
        while (l < r) {
            if (l & 1) vl = op(vl, dat[l++]);
            if (r & 1) vr = op(dat[--r], vr);
            l >>= 1, r >>= 1;
        }
        return op(vl, vr);
    }
    S all_prod() { return dat[1]; }
};
template <class T>
struct BIT {
    // 1-indexed
    int n, beki = 1;
    vector<T> bit;
    BIT(int x) {
        bit.resize(x + 1, 0);
        n = x;
        while (beki * 2 <= n) beki *= 2;
    }
    T sum(int i) {
        T res = 0;
        while (i > 0) {
            res += bit[i];
            i -= i & -i;
        }
        return res;
    }
    T sum(int l, int r) {
        //[l,r]
        return sum(r) - (l == 0 ? 0 : sum(l - 1));
    }
    void add(int i, T x) {
        while (i <= n) {
            bit[i] += x;
            i += i & -i;
        }
    }
    int lowerbound(T w) {
        if (w <= 0) return 0;
        int x = 0;
        for (int k = beki; k > 0; k >>= 1) {
            if (x + k <= n && bit[x + k] < w) {
                w -= bit[x + k];
                x += k;
            }
        }
        return x + 1;
    }
};
template <class T, T (*op)(T, T), T (*e)()>
struct sparsetable {
    vector<vector<T>> table;
    vector<int> logtable;
    sparsetable() = default;
    sparsetable(vector<T> v) {
        int len = 0;
        while ((1 << len) <= v.size()) len++;
        table.assign(len, vector<T>(1 << len));
        for (int i = 0; i < (int)v.size(); i++) table[0][i] = v[i];
        for (int i = 1; i < len; i++) {
            for (int j = 0; j + (1 << i) <= (1 << len); j++) {
                table[i][j] = op(table[i - 1][j], table[i - 1][j + (1 << (i - 1))]);
            }
        }
        logtable.resize(v.size() + 1);
        for (int i = 2; i < logtable.size(); i++) {
            logtable[i] = logtable[(i >> 1)] + 1;
        }
    }
    T query(int l, int r) {
        assert(l <= r);
        if (l == r) return e();
        int len = logtable[r - l];
        return op(table[len][l], table[len][r - (1 << len)]);
    }
};
template <class T, T (*op)(T, T), T (*e)()>
struct disjointsparsetable {
    vector<vector<T>> table;
    vector<int> logtable;
    disjointsparsetable() = default;
    disjointsparsetable(vector<T> v) {
        int len = 0;
        while ((1 << len) <= v.size()) len++;
        table.assign(len, vector<T>(1 << len, e()));
        for (int i = 0; i < (int)v.size(); i++) table[0][i] = v[i];
        for (int i = 1; i < len; i++) {
            int shift = 1 << i;
            for (int j = 0; j < (int)v.size(); j += shift << 1) {
                int t = min(j + shift, (int)v.size());
                table[i][t - 1] = v[t - 1];
                for (int k = t - 2; k >= j; k--) table[i][k] = op(v[k], table[i][k + 1]);
                if (v.size() <= t) break;
                table[i][t] = v[t];
                int r = min(t + shift, (int)v.size());
                for (int k = t + 1; k < r; k++) table[i][k] = op(table[i][k - 1], v[k]);
            }
        }
        logtable.resize(1 << len);
        for (int i = 2; i < logtable.size(); i++) {
            logtable[i] = logtable[(i >> 1)] + 1;
        }
    }
    T query(int l, int r) {
        if (l == r) return e();
        if (l >= --r) return table[0][l];
        int len = logtable[l ^ r];
        return op(table[len][l], table[len][r]);
    };
};
pair<int, int> lcatree_op(pair<int, int> a, pair<int, int> b) { return min(a, b); }
pair<int, int> lcatree_e() { return {1000000000, -1}; }
struct lca_tree {
    int n, size;
    vector<int> in, ord, depth;
    sparsetable<pair<int, int>, lcatree_op, lcatree_e> st;
    lca_tree(vector<vector<int>> g, int root = 0) : n((int)g.size()), size(log2(n) + 2), in(n), depth(n, n) {
        depth[root] = 0;
        function<void(int, int)> dfs = [&](int v, int p) {
            in[v] = (int)ord.size();
            ord.push_back(v);
            for (int u : g[v]) {
                if (u == p) continue;
                if (depth[u] > depth[v] + 1) {
                    depth[u] = depth[v] + 1;
                    dfs(u, v);
                    ord.push_back(v);
                }
            }
        };
        dfs(root, -1);
        vector<pair<int, int>> vec((int)ord.size());
        for (int i = 0; i < (int)ord.size(); i++) {
            vec[i] = make_pair(depth[ord[i]], ord[i]);
        }
        st = vec;
    }
    int lca(int u, int v) {
        if (in[u] > in[v]) swap(u, v);
        if (u == v) return u;
        return st.query(in[u], in[v]).second;
    }
    int dist(int u, int v) {
        int l = lca(u, v);
        return depth[u] + depth[v] - 2 * depth[l];
    }
};
struct auxiliary_tree : lca_tree {
    vector<vector<int>> G;
    auxiliary_tree(vector<vector<int>> &g) : lca_tree(g), G(n) {}
    pair<int, vector<int>> query(vector<int> vs, bool decending = false) {
        // decending:親から子の方向のみ辺を貼る
        assert(!vs.empty());
        sort(vs.begin(), vs.end(), [&](int a, int b) { return in[a] < in[b]; });
        int m = vs.size();
        stack<int> st;
        st.push(vs[0]);
        for (int i = 0; i < m - 1; i++) {
            int w = lca(vs[i], vs[i + 1]);
            if (w != vs[i]) {
                int l = st.top();
                st.pop();
                while (!st.empty() && depth[w] < depth[st.top()]) {
                    if (!decending) G[l].push_back(st.top());
                    G[st.top()].push_back(l);
                    l = st.top();
                    st.pop();
                }
                if (st.empty() || st.top() != w) {
                    st.push(w);
                    vs.push_back(w);
                }
                if (!decending) G[l].push_back(w);
                G[w].push_back(l);
            }
            st.push(vs[i + 1]);
        }
        while (st.size() > 1) {
            int x = st.top();
            st.pop();
            if (!decending) G[x].push_back(st.top());
            G[st.top()].push_back(x);
        }
        // {root,vertex_list}
        return make_pair(st.top(), vs);
    }
    void clear(vector<int> vs) {
        for (int v : vs) G[v].clear();
    }
};
struct Mo {
    int n;
    vector<pair<int, int>> lr;

    explicit Mo(int n) : n(n) {}

    void add(int l, int r) { /* [l, r) */ lr.emplace_back(l, r); }

    template <typename AL, typename AR, typename EL, typename ER, typename O>
    void build(const AL &add_left, const AR &add_right, const EL &erase_left, const ER &erase_right, const O &out) {
        int q = (int)lr.size();
        int bs = n / min<int>(n, sqrt(q));
        vector<int> ord(q);
        iota(begin(ord), end(ord), 0);
        sort(begin(ord), end(ord), [&](int a, int b) {
            int ablock = lr[a].first / bs, bblock = lr[b].first / bs;
            if (ablock != bblock) return ablock < bblock;
            return (ablock & 1) ? lr[a].second > lr[b].second : lr[a].second < lr[b].second;
        });
        int l = 0, r = 0;
        for (auto idx : ord) {
            while (l > lr[idx].first) add_left(--l);
            while (r < lr[idx].second) add_right(r++);
            while (l < lr[idx].first) erase_left(l++);
            while (r > lr[idx].second) erase_right(--r);
            out(idx);
        }
    }

    template <typename A, typename E, typename O>
    void build(const A &add, const E &erase, const O &out) {
        build(add, add, erase, erase, out);
    }
};
template <class S, S (*op)(S, S), S (*e)(), class F, S (*mapping)(F, S), F (*composition)(F, F), F (*id)()>
struct lazy_segtree {
    int _n, sz = 1;
    vector<S> dat;
    vector<F> lazy;
    lazy_segtree(vector<S> a) : _n(int(a.size())) {
        while (sz < _n) sz <<= 1;
        dat.resize(sz * 2, e());
        lazy.resize(sz * 2, id());
        rep(i, _n) dat[sz + i] = a[i];
        for (int i = sz - 1; i >= 1; i--) dat[i] = op(dat[2 * i], dat[2 * i + 1]);
    }
    void eval(int k) {
        dat[k] = mapping(lazy[k], dat[k]);
        if (k < sz) {
            lazy[k * 2] = composition(lazy[k], lazy[k * 2]);
            lazy[k * 2 + 1] = composition(lazy[k], lazy[k * 2 + 1]);
        }
        lazy[k] = id();
    }
    void apply(int a, int b, F f, int k = 1, int l = 0, int r = -1) {
        eval(k);
        if (r == -1) r = sz;
        if (r <= a || b <= l) return;
        if (a <= l && r <= b) {
            lazy[k] = composition(f, lazy[k]);
            eval(k);
            return;
        }
        int m = (l + r) >> 1;
        apply(a, b, f, 2 * k, l, m);
        apply(a, b, f, 2 * k + 1, m, r);
        dat[k] = op(dat[2 * k], dat[2 * k + 1]);
    }
    S prod(int a, int b, int k = 1, int l = 0, int r = -1) {
        eval(k);
        if (r == -1) r = sz;
        if (r <= a || b <= l) return e();
        if (a <= l && r <= b) return dat[k];
        int m = (l + r) >> 1;
        S vl = prod(a, b, 2 * k, l, m);
        S vr = prod(a, b, 2 * k + 1, m, r);
        return op(vl, vr);
    }
};

template <class S, S (*op)(S, S), S (*e)()>
struct dual_segtree {
    int sz = 1, log = 0;
    vector<S> lz;
    dual_segtree(vector<S> a) {
        int n = a.size();
        while (sz < n) {
            sz <<= 1;
            log++;
        }
        lz.assign(sz << 1, e());
        for (int i = 0; i < n; i++) lz[i + sz] = a[i];
    }
    void push(int k) {
        int b = __builtin_ctz(k);
        for (int d = log; d > b; d--) {
            lz[k >> d << 1] = op(lz[k >> d << 1], lz[k >> d]);
            lz[k >> d << 1 | 1] = op(lz[k >> d << 1 | 1], lz[k >> d]);
            lz[k >> d] = e();
        }
    }
    void apply(int l, int r, S x) {
        l += sz, r += sz;
        push(l);
        push(r);
        while (l < r) {
            if (l & 1) {
                lz[l] = op(lz[l], x);
                l++;
            }
            if (r & 1) {
                r--;
                lz[r] = op(lz[r], x);
            }
            l >>= 1, r >>= 1;
        }
    }
    S get(int k) {
        k += sz;
        S res = e();
        while (k) {
            res = op(res, lz[k]);
            k >>= 1;
        }
        return res;
    }
};

/*
#include <atcoder/string>
int string_period(string s) {
    int n = s.size();
    auto z = atcoder::z_algorithm(s);
    for (int i = 1; i < n; i++) {
        if (n % i == 0 && z[i] == n - i) return i;
    }
    return n;
}
*/
struct LowLink {
    vector<vector<int>> g;
    vector<int> ord, low, out;
    vector<bool> used;
    vector<pair<int, int>> bridge;
    vector<pair<int, int>> articulation;
    int unions;
    LowLink(vector<vector<int>> g) : g(g) {
        int n = (int)g.size();
        ord.resize(n);
        low.resize(n);
        out.resize(n);
        used.resize(n);
        unions = 0;
        int t = 0;
        for (int i = 0; i < n; i++) {
            if (!used[i]) {
                dfs(i, t, -1);
                unions++;
            }
        }
    }
    void dfs(int v, int &t, int par) {
        used[v] = true;
        ord[v] = t++, low[v] = ord[v];
        int cnt = 0;
        bool par_back = false;
        for (int to : g[v]) {
            if (!used[to]) {
                dfs(to, t, v);
                low[v] = min(low[v], low[to]);
                if (ord[v] < low[to]) bridge.push_back(minmax(v, to));
                if (ord[v] <= low[to]) cnt++;
            } else if (to != par || par_back) {
                low[v] = min(low[v], ord[to]);
            } else
                par_back = true;
        }
        if (par != -1) cnt++;
        if (cnt >= 2) articulation.push_back({v, cnt});
        out[v] = t;
    }
};
template <typename T>
T rand(T l, T r) {
    static mt19937 mt(random_device{}());
    if constexpr (is_integral_v<T>) {
        uniform_int_distribution<T> dist(l, r);
        return dist(mt);
    } else if constexpr (is_floating_point_v<T>) {
        uniform_real_distribution<T> dist(l, r);
        return dist(mt);
    }
}
void solve() {
    ll m,a;
    cin>>m>>a;
    if(m==0&&a==0)exit(0);
    ll g=gcd(m,a);
    ll s=m/g,t=a/g;
    t=modinv(t,s);
    //t+ks (k=0,1,...,g-1)
    //such that
    //gcd(g,t+ks)=1
    //phi(g) !?
    ll ans=g;
    for(ll i=2;i*i<=g;i++){
        if(g%i==0&&gcd(i,s)==1){
            ans/=i;
            ans*=(i-1);
        }
        while(g%i==0){
            g/=i;
        }
    }
    if(g>1&&gcd(g,s)==1){
        ans/=g;
        ans*=(g-1);
    }
    cout<<ans<<endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    /*int t;
    cin >> t;
    while (t--) */
    while (1) solve();
}
accuracy: 1
time_ms: 50
memory_kb: 3348
final_rank: 2

code_snippet: #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define eb emplace_back
using namespace std;
using ll = long long;
using ld = long double;
using vl = vector<long long>;
using vvl = vector<vector<long long>>; using vs = vector<string>;
using pl = pair<long long, long long>;
template <typename T> inline bool chmin(T& a, const T& b) {bool compare = a > b; if (a > b) a = b; return compare;}
template <typename T> inline bool chmax(T& a, const T& b) {bool compare = a < b; if (a < b) a = b; return compare;}
template<class T>using rp_queue=priority_queue<T,vector<T>,greater<T>>;
template <typename T> T gcd(T a, T b) {if (b == 0)return a; else return gcd(b, a % b);}
template <typename T> inline T lcm(T a, T b) {return a /gcd(a, b)*b;}
const ll INF = 1LL << 60;
const ld PI = acos(-1);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec);
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr);
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const pair<T, U> &pa);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa);
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp);
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp);
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl);
 
template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; }
template <class... T> std::istream &operator>>(std::istream &is, std::tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; }
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa) { return os << '(' << pa.first << ',' << pa.second << ')'; }
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#ifdef LOCAL
const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[1;31m", BRIGHT_CYAN = "\033[1;36m", NORMAL_CROSSED = "\033[0;9;37m", RED_BACKGROUND = "\033[1;41m", NORMAL_FAINT = "\033[0;2m";
#define dbg(x) std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl
#define dbgif(cond, x) ((cond) ? std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl : std::cerr)
#else
#define dbg(x) ((void)0)
#define dbgif(cond, x) ((void)0)
#endif
void solve();
int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  cout<<fixed<<setprecision(15);
  int num_tc = 1;
  //cin >> num_tc;
  rep(tc,num_tc){
    //cout << "Case #" << tc+1 << ": " ;// << endl;
    solve();
  }
}
long long modinv(long long a, long long m) {
    long long b = m, u = 1, v = 0;
    while (b) {
        long long t = a / b;
        a -= t * b; swap(a, b);
        u -= t * v; swap(u, v);
    }
    u %= m; 
    if (u < 0) u += m;
    return u;
}
vl factor(ll N){
  vl res;
  for(ll a=2;a*a<=N;a++){
    if(N%a==0){
      res.push_back(a);
      while(N%a==0){
        N/=a;
      }
    }
  }
  if(N!=1)res.push_back(N);
  return res;
}
void solve(){
  while(true){
    ll M,A;cin>>M>>A;
    if(M==0&&A==0)return;
    ll g = gcd(M,A);
    ///gで割れば逆元が存在するのでOK
    ll ans =g ;
    for(auto p:factor(g)){
      if(gcd(g,M/g)%p==0)continue;
      ans/=p;
      ans*=p-1;
    }
    cout<<ans<<endl;
  }
}
accuracy: 1
time_ms: 60
memory_kb: 3460
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;

int main(){
  while(1){
    long long M, A;
    cin >> M >> A;
    if(M == 0 && A == 0){
      return 0;
    }
    long long g = gcd(M, A);
    long long m = M;
    long long d = M / g;
    for(long long i = 2; i * i <= m; i++){
      if(m % i == 0){
        if(d % i != 0){
          g /= i;
          g *= (i - 1);
        }
        while(m % i == 0){
          m /= i;
        }
      }
    }
    if(m != 1 && d % m != 0){
      g /= m;
      g *= (m - 1);
    }
    cout << g << endl;
  }
}
accuracy: 1
time_ms: 220
memory_kb: 3368
final_rank: 16

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>
using namespace std;

using ll = long long;
using i64 = long long;
using pll = pair<ll,ll>;
using plll = pair<pll,ll>;
using pii =pair<int,int>;

constexpr ll mod = 1000000007;

int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int dX[4]={1,0,-1,0};
int dY[4]={0,-1,0,1};



//library

template<typename T>
T extgcd(T a,T b,T& x,T& y){
    if (!b) { x=1;y=0;return a; }
    ll d=extgcd(b,a%b,y,x);
    y-=(a/b)*x; return d;
}

//end



using Graph =vector<vector<ll>>;

int main(){
    while(true){
        ll m,a;
        cin>>m>>a;
        if (m==0)break;
        ll g=gcd(m,a);
        ll x0,y0;
        extgcd(a/g,m/g,x0,y0);
        //cout<<x0<<endl;
        ll l=(m-x0)/(m/g)-((1-x0+(m/g)-1)/(m/g))+1;
        ll mg=m/g;
        for (int i=2; i<10000000; i++){
            if (i*i>m)break;
            if (m%i==0){
                while (m%i==0)m/=i;
                if (mg%i){
                    l/=i;
                    l*=(i-1);
                }
            }
        }
        if (m>1){
            if (mg%m){
                l/=m;
                l*=m-1;
            }
        }
        cout<<l<<endl;








    }


}
accuracy: 1
time_ms: 4820
memory_kb: 3336
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;

int main() {
    while(true) {
        long long M, A;
        cin >> M >> A;

        if(M == 0) return 0;

        long long g = gcd(M, A);
        long long B = M / g;

        set<long long> Mp;
        long long m = M;
        for(long long i = 2; i * i <= M; i++) {
            while(m % i == 0) {
                m /= i;
                Mp.insert(i);
            }
        }

        if(m != 1) Mp.insert(m);

        set<long long> Bp;
        long long b = B;
        for(long long i = 2; i * i <= B; i++) {
            while(b % i == 0) {
                b /= i;
                Bp.insert(i);
            }
        }

        if(b != 1) Bp.insert(b);

        long long ans = g;
        for(auto p : Mp) {
            if(!Bp.count(p)) {
                ans /= p;
                ans *= (p - 1);
            }
        }

        cout << ans << endl;

    }


    return 0;
}
accuracy: 1
time_ms: 2010
memory_kb: 3368
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = (int)1e9 + 1001010;
const ll llINF = (long long)4e18 + 22000020;
const string endn = "\n";
template <class T> inline auto vector2(size_t i, size_t j, const T &init = T()) {return vector(i, vector<T>(j, init));}
const string ELEM_SEPARATION = " ", VEC_SEPARATION = endn;
template<class T> istream& operator >>(istream &i, vector<T> &A) {for(auto &I : A) {i >> I;} return i;}
template<class T> ostream& operator <<(ostream &o, const vector<T> &A) {int i=A.size(); for(const auto &I : A){o << I << (--i ? ELEM_SEPARATION : "");} return o;}
template<class T> ostream& operator <<(ostream &o, const vector<vector<T>> &A) {int i=A.size(); for(const auto &I : A){o << I << (--i ? VEC_SEPARATION : "");} return o;}
template<class T> vector<T>& operator ++(vector<T> &A, int n) {for(auto &I : A) {I++;} return A;}
template<class T> vector<T>& operator --(vector<T> &A, int n) {for(auto &I : A) {I--;} return A;}
template<class T, class U> bool chmax(T &a, const U &b) {return ((a < b) ? (a = b, true) : false);}
template<class T, class U> bool chmin(T &a, const U &b) {return ((a > b) ? (a = b, true) : false);}
ll floor(ll a, ll b){if (b < 0) a = -a, b = -b; if(a >= 0) return a / b; else return (a + 1) / b - 1;}
ll ceil(ll a, ll b){if (b < 0) a = -a, b = -b; if(a > 0) return (a - 1) / b + 1; else return a / b;}
ll bit(unsigned long long val, unsigned long long digit){return (val >> digit) & 1;}
#ifdef DEBUG
#include <debug_slephy.cpp>
#else
#define debug(...)
#endif
// ================================== ここまでテンプレ ==================================

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

void solve(){
    ll M, A; cin >> M >> A;
    if(M == 0) exit(0);
    ll g = gcd(M, A);
    ll m = M / g;
    ll Md = M;
    while(gcd(Md, m) > 1) Md /= gcd(Md, m);
    debug(M, m, g, Md, phi(Md));
    ll ans = phi(Md) * (g / Md);
    cout << ans << endl;
}

int main(int argc, char *argv[]){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    while(true) solve();
    return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 3460
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (long long i = 0; i < (long long)(n); i++)
#define rrep(i,start,end) for (long long i = start;i >= (long long)(end);i--)
#define repn(i,end) for(long long i = 0; i <= (long long)(end); i++)
#define reps(i,start,end) for(long long i = start; i < (long long)(end); i++)
#define repsn(i,start,end) for(long long i = start; i <= (long long)(end); i++)
#define each(p,a) for(auto &p:a)
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef vector<long long> vll;
typedef vector<pair<long long ,long long>> vpll;
typedef vector<vector<long long>> vvll;
typedef set<ll> sll;
typedef map<long long , long long> mpll;
typedef pair<long long ,long long> pll;
typedef tuple<long long , long long , long long> tpl3;
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define Str(...) string __VA_ARGS__; input(__VA_ARGS__)
#define Ch(...) char __VA_ARGS__; input(__VA_ARGS__)
#define all(a)  (a).begin(),(a).end()
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
#define sz(x) (int)x.size()
// << std::fixed << std::setprecision(10)
const ll INF = 1LL << 60;
const ld EPS = 1e-9;
 
inline ll lfloor(ll x,ll m){return (x - ((x % m+ m)%m))/m;}
inline ll positive_mod(ll a,ll m){return (a % m + m)%m;}
inline ll popcnt(ull a){ return __builtin_popcountll(a);}
template<class T> bool chmin(T& a, T b){if(a > b){a = b;return true;}return false;}
template<class T> bool chmax(T& a, T b){if(a < b){a = b;return true;}return false;}
template<typename T> std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
template<typename T> std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
template<typename T1, typename T2>std::ostream &operator<< (std::ostream &os, std::pair<T1,T2> p){os << "{" << p.first << "," << p.second << "}";return os;}
template<class... T>void input(T&... a){(cin >> ... >> a);}
void print(){cout << endl;}
template<class T, class... Ts>void print(const T& a, const Ts&... b){cout << a;((cout << ' ' << b), ...);cout << endl;}
template<class T> void pspace(const T& a){ cout << a << ' ';}
void perr(){cerr << endl;}
template<class T, class... Ts>void perr(const T& a, const Ts&... b){cerr << a;((cerr << ' ' << b), ...);cerr << endl;}
void yes(bool i = true){ return print(i?"yes":"no"); }
void Yes(bool i = true){ return print(i?"Yes":"No"); }
void YES(bool i = true){ return print(i?"YES":"NO"); }
template <class T> vector<T> &operator++(vector<T> &v) {for(auto &e : v) e++;return v;}
template <class T> vector<T> operator++(vector<T> &v, signed) {auto res = v;for(auto &e : v) e++;return res;}
template <class T> vector<T> &operator--(vector<T> &v) {for(auto &e : v) e--;return v;}
template <class T> vector<T> operator--(vector<T> &v, signed) {auto res = v;for(auto &e : v) e--;return res;}
//grid探索用
vector<ll> _ta = {0,0,1,-1,1,1,-1,-1};
vector<ll> _yo = {1,-1,0,0,1,-1,1,-1};
bool isin(ll now_i,ll now_j,ll h,ll w){return (0<=now_i && now_i < h && 0 <= now_j && now_j < w);}
  
ll lpow(ll x,ll n){ll ans = 1;while(n >0){if(n & 1)ans *= x;x *= x;n >>= 1;}return ans;}
ll Modlpow(ll x,ll n,ll m){ll ans = 1;ll a = x%m;while(n >0){if(n & 1){ans *= a;ans%= m;}a *= a;a %= m;n >>= 1;}return ans;} 
const ll MOD9 = 998244353LL;
const ll MOD10 = 1000000007LL;

// for AOJ or ICPC or etc..
// 全部が0だったらtrueを返す
template<class Tp> bool zero (const Tp &x) {return x == 0;}
template<class Tp, class... Args> bool zero (const Tp &x, const Args& ...args) {return zero(x) and zero(args...);}

//返り値gcd(a,b)
//ax + by = gcd(a,b)を満たすx,yを参照で返す
ll extGCD(ll a,ll b,ll &x, ll&y){
 if(b == 0){
   x = 1;
   y = 0;
   return a;
 }
 ll d = extGCD(b,a % b,y,x);
 y -= a/b * x;
 return d;
}
 
// リターン値を (r, m) とすると解は x ≡ r (mod. m)
// 解なしの場合は (0, -1) を返す
// b:あまり、m:法
pair<ll,ll> crt(const vector<ll> &b,const vector<ll> &m){
 assert(b.size() == m.size());
 ll r = 0; ll lcm_m = 1;
 rep(i,b.size()){
   ll p,q;
   ll d = extGCD(lcm_m,m[i],p,q);
   if((b[i] - r) % d != 0)return {0,-1};//解なし
   ll tmp = (b[i]-r)/d * p % (m[i]/d);//多分オーバーフロー対策
   r += lcm_m * tmp;
   lcm_m *= m[i]/d;
 }
 return {(r % lcm_m+lcm_m)%lcm_m,lcm_m};
}

//素因数分解
map<ll,ll> enumpr(ll n) {
 map<ll,ll> V;
 for(ll i=2;i*i<=n;i++) {
    while(n%i==0){
      V[i]++;
      n/=i;
    } 
  }
 if(n>1) V[n]++;
 return V;
}


ll gyakugen(ll a,ll b){
  //aのmod bでの逆元
  ll x,y;
  extGCD(a,-b,x,y);
  return x;
}

// 変数をちゃんと全部受け取る！
void solve(ll m,ll a){
  ll g = gcd(m,a);
  if(g == 1){
    cout << 1 << endl;
    return ;
  }

  map<ll,ll> enu = enumpr(m);

  vll ps;//pの候補
  each(p,enu){
    ps.push_back(p.first);
  }

  ll siz = ps.size();

  vll rs(siz);

  rep(i,siz){
    ll p = ps[i];
    if(gcd(p,m/g) == 1){
      //互いに素
      rs[i] = -(gyakugen(a/g,m/g)) * gyakugen(m/g,p);
      rs[i] = positive_mod(rs[i],p);
    }else{
      rs[i] = -INF;
    }
  }

  //いらないの消す
  vll tmpps,tmprs;
  rep(i,siz){
    if(rs[i] != -INF){
      tmpps.push_back(ps[i]);
      tmprs.push_back(rs[i]);
    }
  }
  swap(tmpps,ps);
  swap(tmprs,rs);
  siz = ps.size();

  //bit全探索
  ll ans = g;
  reps(i,1,1 << siz){
    vll rss,pss;//あまり、p
    rep(j,siz){
      if(i >> j & 1){
        rss.push_back(rs[j]);
        pss.push_back(ps[j]);
      }
    }
    auto [r,p] = crt(rss,pss);
    //
    ll num = (g-1)/p;
    ll rem = (g-1) % p;
    if(r != 0){
      if(rem >= r){
        num++;
      }
    }else{
    }
    // perr(popcnt(i),p,r,num);
    if(r == 0){
      num++;
    }
    if(popcnt(i) % 2 == 1){
      //引く
      ans -= num;
    }else{
      //足す
      ans+= num;
    }
  }
  
  cout << ans << endl;



}
 
int main(){
  ios::sync_with_stdio(false);cin.tie(nullptr);
  while(true){
    LL(m,a);//変数数調整
    if(zero(m,a))break;
    solve(m,a);
  }
}
accuracy: 1
time_ms: 80
memory_kb: 3468
final_rank: 11

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for (long long i=0;i<n;i++)
#define loop(i,m,n) for(long long i=m;i<=n;i++)
#define range(value,range) for(const auto &value : range)
#define ll long long
#define vl vector<long long>
#define vvl vector<vector<long long>>
#define vdbg(a) rep(ii,a.size()){cout<<a[ii]<<" ";}cout<<endl;
#define vvdbg(a) rep(ii,a.size()){rep(jj,a[ii].size()){cout<<a[ii][jj]<<" ";}cout<<endl;}
#define inf 4000000000000000000LL
#define mod 998244353LL

//整数同士の累乗の計算をする。
ll power(ll A, ll B) {
	ll result = 1;
	for (ll i=0;i<B;i++){
		result *= A;
	}
	return result;
}

//オイラーのトーシェント関数。N以下のNと互いに素な物の数を返す。
ll euler(ll n){
	unordered_map<ll,ll> factors;
	ll tmp=n;
	while (tmp % 2 == 0) {
		factors[2]++;
		tmp /= 2;
	}
	for (ll i=3; i*i<=tmp;i+=2) {
		while (tmp%i == 0) {
			factors[i]++;
			tmp/= i;
		}
	}
	if (tmp > 2)factors[tmp]++;
	ll ans=1;
	for(const auto & val:factors){
		ans*=power(val.first,val.second-1)*(val.first-1);
	}
	return ans;
}


map<ll,ll> makeMapPrime(ll n){
	map<ll,ll> factors;
	while (n % 2 == 0) {
		factors[2]++;
		n /= 2;
	}
	for (ll i=3; i*i<=n;i+=2) {
		while (n%i == 0) {
			factors[i]++;
			n /= i;
		}
	}
	if (n > 2) {
		factors[n]++;
	}
	return factors;
}


ll solve(){
	ll m,a;
	cin>>m>>a;
	if(m==0)return 1;
	ll g=gcd(m,a);

	//合同式の約分をし、m/gの素因数の書き出し
	map<ll,ll>p=makeMapPrime(m/g);

	//mをgと互いに素になるまで約数の消去をする。(周期内の存在数)
	for(const auto &val:p){
		while(m%val.first==0)m/=val.first;
	}
	
	//オイラー関数で１回の周期内の個数を求めている。
	//g/mが何周期存在するかを計算している。
	ll ans=(g/m)*euler(m);

	cout<<ans<<endl;

	return 0;
}

int main(){
	while(1){
		if(solve()==1)break;
	}
	return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 3352
final_rank: 4

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for (long long i=0;i<n;i++)
#define loop(i,m,n) for(long long i=m;i<=n;i++)
#define range(value,range) for(const auto &value : range)
#define ll long long
#define vl vector<long long>
#define vvl vector<vector<long long>>
#define vdbg(a) rep(ii,a.size()){cout<<a[ii]<<" ";}cout<<endl;
#define vvdbg(a) rep(ii,a.size()){rep(jj,a[ii].size()){cout<<a[ii][jj]<<" ";}cout<<endl;}
#define inf 4000000000000000000LL
#define mod 998244353LL

//整数同士の累乗の計算をする。
ll power(ll A, ll B) {
	ll result = 1;
	for (ll i=0;i<B;i++){
		result *= A;
	}
	return result;
}

//オイラーのトーシェント関数。N以下のNと互いに素な物の数を返す。
ll euler(ll n){
	unordered_map<ll,ll> factors;
	ll tmp=n;
	while (tmp % 2 == 0) {
		factors[2]++;
		tmp /= 2;
	}
	for (ll i=3; i*i<=tmp;i+=2) {
		while (tmp%i == 0) {
			factors[i]++;
			tmp/= i;
		}
	}
	if (tmp > 2)factors[tmp]++;
	ll ans=1;
	for(const auto & val:factors){
		ans*=power(val.first,val.second-1)*(val.first-1);
	}
	return ans;
}


map<ll,ll> makeMapPrime(ll n){
	map<ll,ll> factors;
	while (n % 2 == 0) {
		factors[2]++;
		n /= 2;
	}
	for (ll i=3; i*i<=n;i+=2) {
		while (n%i == 0) {
			factors[i]++;
			n /= i;
		}
	}
	if (n > 2) {
		factors[n]++;
	}
	return factors;
}


ll solve(){
	ll m,a;
	cin>>m>>a;
	if(m==0)return 1;
	ll g=gcd(m,a);
	map<ll,ll>p=makeMapPrime(m/g);
	ll k=m/g;

	range(val,p){
		while(m%val.first==0)m/=val.first;
	}
	
	//オイラー関数で１回の周期内の個数を求めている。
	ll ans=(g/m)*euler(m);

	cout<<ans<<endl;

	return 0;
}

int main(){
	while(1){
		if(solve()==1)break;
	}
	return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 3352
final_rank: 4