Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way:  (for i ≥ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and  denotes the operation of taking the remainder of division.For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, ....Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2.Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i ≥ k: ri = ri + t.

The single line of the input contains four integers a, b, m and r0 (1 ≤ m ≤ 105, 0 ≤ a, b ≤ 1000, 0 ≤ r0 < m), separated by single spaces.

Print a single integer — the period of the sequence.

NoteThe first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ...In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...

#include <cstdio>
#include <iostream>
using namespace std;
int a,b,m,x,h[100001];
int main(){
	scanf("%d%d%d%d",&a,&b,&m,&x);
	for(int i=1;;++i){
		x=(a*x+b)%m;
		if(h[x]){
			printf("%d",i-h[x]);
			return 0;
		}
		h[x]=i;
	}
}

#include<iostream>

using namespace std;

int main(){

    int Z,I,M,L;
    int x1,x2,n,m,caso;
        cin>>Z>>I>>M>>L;

        x1=L;
        x2=L;

        m=0;

        do{
            x1=(x1*Z+I)%M;
            x2=(x2*Z+I)%M;
            x2=(x2*Z+I)%M;
            m++;
        }while(x1!=x2);

       x1=x2=L;
        for(int i=0;i<m;i++) x2=(x2*Z+I)%M;

        while(x1!=x2){
            x1=(x1*Z+I)%M;
            x2=(x2*Z+I)%M;
        }

        x2=x1;
        n=0;

        do{
            x2=(x2*Z+I)%M;
            n++;
        }while(x2!=x1);
        cout<<n;
    return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<iterator>
#include<cmath>
#include<string>
#include<sstream>
#include<cstring>
#include<ctype.h>
#include<iomanip>
#include<functional>
#include<bitset>
#include<stdio.h>
#include<fstream>
#include<regex>
#include<stdlib.h>
#include<math.h>
#include<ctime>
#include<array>
#include<string>
#include<cstdio>

#define lop(i,n)   for(ll i=0;i<n;++i)
#define R_(s)      freopen(s, "r", stdin)
#define W_(s)      freopen(s, "w", stdout)
#define R_W        R_("input.txt"),W_("output.txt")
#define PI         3.14159265358979323846
#define ll         long long
#define ld         long double
#define sz(v)      (ll)v.size()
#define ii         pair<ll,ll>
#define vii        vector<ii>
#define vi         vector<int>
#define vll        vector<ll>
#define vs         vector<string>
#define vvii       vector<vector<ii>>
#define vvi        vector<vector<int>>
#define vvll       vector<vector<ll>>
#define all(v)     v.begin(),v.end()
#define clr(a,b)   memset(a,b,sizeof a)
#define sc(n)      scanf("%d",&n)
#define scl(n)     scanf("%lld",&n)
#define pr1(n)     printf("%d\n",n)
#define pr2(n)     printf("%d " ,n)
#define pr3(n)     cout<<fixed<<setprecision(3)<<n<<endl
#define endl       "\n"
#define DFS_GRAY  -1
#define DFS_WHITE  0
#define DFS_BLACK  1
#define oo  1e9
#define OO  1e18
using namespace std;
int dr[] = { 0, 0, 1, -1, -1, -1, 1, 1 };
int dc[] = { 1, -1, 0, 0, -1, 1, -1, 1 };
ll mod = 1e9 + 7;
const int MAX = 1e6 + 7;
map<int, pair<int,int>>mp;
int main()
{
    int a, b, r, m; cin >> a >> b >> m >> r;
    int last = r, i = 0; mp[last].first++, mp[last].second = i;
    while (1)

    {
        i++;
        int cur = (last*a + b) % m;
        if (mp[cur].first != 0)
        {
            cout << i - mp[cur].second << endl;
            return 0;
        }
        mp[cur].first++, mp[cur].second = i;
        last = cur;
    }
}

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
typedef pair<int,int> pii;
void R(int &x){scanf("%d",&x);}
void R(char *x){scanf("%s",x);}
void R(ll &x){scanf("%lld",&x);}
void R(double &x){scanf("%lf",&x);}
void RI(){}
template<typename I,typename... T>
void RI(I &x,T&... tail){R(x);RI(tail...);}
#define pb push_back
#define mkp make_pair
#define F first
#define S second

int a,b,m,r0,r1;
ll ans;
map<int,pair<bool,int>> mp;
void read()
{
    RI(a,b,m,r0);
}
void build()
{
    mp[r0]=mkp(true,0);
    for(int i=1;;i++)
    {
        r1=(a*r0+b)%m;
        if(mp[r1].F==true)
        {
            ans=i-mp[r1].S;
            return;
        }
        mp[r1]=mkp(true,i);
        swap(r1,r0);
    }
}
void sol()
{
    printf("%lld\n",ans);
}
int main()
{
    read();
    build();
    sol();
    return 0;
}

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5;
int mod,a,b,m[N],p;
signed main() {
#ifdef _DEBUG
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>a>>b>>mod>>p;
	m[p]=1;
	for(int i=2;;i++){
		int el=(a*p+b)%mod;
		if(m[el]){
			cout<<i-m[el];
			return 0;
		}
		m[el]=i;
		p=el;
	}
}

/// ///////////////// BISMILLAH /////////////////////////////

#include<bits/stdc++.h>
using namespace std;
long k,a,b,r,m;
map<int,int> mp;
int main()
{
            ios_base::sync_with_stdio(false);
             cin>> a>> b>> m>> r;
              while(true)
              {
                   k++, r= (a*r+b)%m;
                   if(mp[r]) {cout<< k-mp[r]; return 0;}
                   mp[r]=k;
              }
          return 0;
}

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

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

int t[100005];

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	cerr.tie(nullptr);

	int a, b, m, r0;
	cin >> a >> b >> m >> r0;
	int r = r0;
	for (int i=1;; i++) {
		if (t[r])
			return cout << i - t[r], 0;
		else
			t[r] = i;
		r = (a*1ll*r + b) % m;
	}
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define pi 3.141592653589

ll power(ll b,ll e,ll m)
{
    if(e==0) return 1;
    if(e&1) return b*power(b*b%m,e/2,m)%m;
    return power(b*b%m,e/2,m);
}
ll power(ll b,ll e)
{
    if(e==0) return 1;
    if(e&1) return b*power(b*b,e/2);
    return power(b*b,e/2);
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll a,b,m,r,r1,p;
    cin>>a>>b>>m>>r;
    map<ll,ll> ma;
    for(auto i=1;i<1000000;i++)
    {
        r1=(a*r+b)%m;
        r=r1;
        if(ma[r1]==0)
            ma[r1]=i;
        else
        {
            p=i-ma[r1];
            break;
        }
    }
    cout<<p;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
int main(){
	int a,b,m,r;
	cin>>a>>b>>m>>r;
	int curr = (r * a + b) %m,cnt=1;
	vector<int> all(m+1,0);
	while(!all[curr]){
		all[curr]=cnt++;
		curr = (curr*a + b)%m;
		//cout<<curr<<' ';
	}
	cout<<cnt - all[curr]<<endl;
}

#include <cstdio>

bool hash[111111];

int a, b, m;
int r[111111];

int main()
{
    //freopen("input.txt", "r", stdin);
    scanf("%d %d %d %d", &a, &b, &m, &r[0]);
    int el = -1;
    int N = 0;

    for(int i = 1; i < 111111; i++)
    {
        r[i] = (a * r[i-1] + b) % m;
        //printf("%d ", r[i]);
        if (hash[r[i]] == true)
        {
            el = r[i];
            N = i;
            break;
        }
        else
        {
            hash[r[i]] = true;
        }
    }

    int lung;

    for(int i = 1; i < N; i++)
    {
        if (r[i] == el)
        {
            lung = N - i;
            printf("%d\n", N - i);
            //return 0;
            break;
        }
    }

    return 0;
}

#include <fstream>
#include <stdio.h>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <string>
#include <cstring>
#include <cmath>

using namespace std;

#define forn(i,n) for (int i=0; i<int(n); ++i)
#define forl(i,n) for (int i=int(n)-1; i>=0; --i)
#define fore(i,a,b) for (int i=int(a); i<=int(b); ++i)
#define all(a) a.begin(), a.end()
#define allr(a) a.rbegin(), a.rend()
#define pb push_back
#define mp make_pair
#define ft first
#define sd second
const int INF = (int)1e9;
const long long INF64 = (long long) 1e18;
const long double eps = 1e-9;
const long double pi = 3.14159265358979323846;
#define ll long long
#define uint unsigned int
#define vi vector <int>
#define pii pair <int,int>
#define vt(a) vector <a>
#define vs vector <string>
#define qi queue <int>
#define sz(a) (int)a.size()
int p[100005];
int a, b, m, r0;
int main () {
#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
#endif
	cin >> a >> b >> m >> r0;
	memset(p, -1, sizeof(p));
	for(int i=1;;i++) {
		r0 = (a*r0 + b)%m;
		if (p[r0]!=-1) {
			cout<<i-p[r0];
			return 0;
		} else p[r0]=i;
	}
}

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
	int a,b,m,r,c[100000]={0};
	cin >> a >> b >> m >> r;
	for(int i=0;1;i++)
	{
		r=(a*r+b)%m;
		if(c[r]!=0)
		{
			cout<<i-c[r];
			return 0;
		}
		c[r]=i;
	}
}

#include <iostream>
#include <map>

using namespace std;

int main() {
  std::cin.tie(0);
  std::ios::sync_with_stdio(false);

  int a, b, m, r;
  cin >> a >> b >> m >> r;

  map<int, int> mp;
  for (int i = 0; i <= m; i++) {
    if (mp.find(r) != mp.end()) {
      cout << i - mp[r] << endl;
      return 0;
    }
    mp[r] = i;
    r = (a * r + b) % m;
  }
  return 0;
}

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

//void probel(int i){
    //cout<<' '<<i;
//}

int main(){
    int a,b;
    long m,r0,k;
    vector<int> str;
    cin >> a >> b >> m >> r0;
    for(int i=0;i<10000000;++i){
        r0 = (r0*a + b)%m;
        str.push_back(r0);
    }
    int i=0, j=1;
    for(i=0;i<10000000;++i){
        for(j;j<10000000;++j){
            if(str[i]==str[j]){
            k=j-i;goto M;
            }
        }
    j=i+2;
    }
    //cout << "Znachenie:"<<endl;
    //for_each (str.begin(), str.end(), probel);
    M:cout<<k<<endl;
    //system("pause");
}

#include <bits/stdc++.h>
using namespace std;
int a, b, m, x, i;
int vis[100005];
int main(){
	std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//	freopen("test_file/in.txt", "r", stdin);
//	freopen("test_file/out.txt", "w", stdout);
	memset(vis, 0, sizeof(vis));
	cin >> a >> b >> m >> x;
	for (i = 1; !vis[(a*x+b)%m]; i++) vis[(a*x+b)%m] = i, x = (a*x+b)%m;
	cout << i-vis[(a*x+b)%m];
	return 0;
}
/**   +
*　　┏┓　　　┏┓+ +
*　┏┛┻━━━┛┻┓ + +
*　┃　　　　　　　┃
*　┃　　　━　　　┃ ++ + + +
*  ████━████+
*  ◥██◤　◥██◤ +
*　┃　　　┻　　　┃
*　┃　　　　　　　┃ + +
*　┗━┓　　　┏━┛
*　　　┃　　　┃ + + + +Code is far away from
*　　　┃　　　┃ + bug with the animal protecting
*　　　┃　 　 ┗━━━┓ 神兽保佑,代码无bug
*　　　┃ 　　　　　　 ┣┓
*　　  ┃ 　　　　　 　┏┛
*　    ┗┓┓┏━┳┓┏┛ + + + +
*　　　　┃┫┫　┃┫┫
*　　　　┗┻┛　┗┻┛+ + + +
*/

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <memory.h>
using namespace std;
long long a,b,m,r0;
long long first[1000005];
int main()
{
    cin>>a>>b>>m>>r0;
    memset(first,0,sizeof first);
    first[r0]=1;
    for (long long i=2;;i++)
    {
        r0=(r0*a+b)%m;
        if (first[r0]!=0)
        {cout<<(i-first[r0])<<endl;break;}
        else
        {first[r0]=i;}
    }
}

#include "bits/stdc++.h"
#include "ext/pb_ds/assoc_container.hpp"
#include "ext/pb_ds/tree_policy.hpp"
using namespace __gnu_pbds;
using namespace std;

namespace basic{
    using ll =long long int;
    #define imax INT_MAX
    #define lmax LLONG_MAX
    #define pb push_back
    #define ld long double
    #define pii pair<int,int>
    #define pll pair<ll,ll>
    #define v vector
    #define vll vector<ll>
    #define vv(a) vector<vector<a>>
    #define cld complex<ld>
    #define cll complex<ll>
    #define all(x) (x).begin(),(x).end()
    #define rall(x) (x).rbegin(),(x).rend()
    #define mini(a) *min_element(all(a))
    #define maxi(a) *max_element(all(a))
    #define sum_vec(a) accumulate(all(a),0LL)
    #define trans_lower(s) transform(all(s),s.begin(),::tolower)
    #define trans_upper(s) transform(all(s),s.begin(),::toupper)
    #define sz(a) ((ll)a.size())
    #define Pi acos(-1)
    #define f first
    #define se second
    #define lb lower_bound
    #define ub upper_bound
    #define endl "\n"
    #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
    #define tc int t=0;cin>>t;while(t--)
    #define tc1 int t=1;while(t--)
    #define tc_case int t=0,a_t=0;cin>>t;a_t=t;while(t--)
    #define case(a) cout<<"Case #"<<a_t-t<<": "<<a<<endl;
    const ll inf = 1e9+7;
    template<class T>void refresh(T &a,ll n){
        assert(n>=0);
        a.clear();a.resize(n);
    }
    template<class X,class Y>void refresh_with_value(X &a,ll n,Y value){
        assert(n>=0);
        a.clear();a.resize(n,value);
    }
    template<class X>void Unique(X &a){
        sort(all(a));
        a.erase(unique(all(a)),a.end());
    }
    template<class T> ll uniq_size(T a){
        sort(all(a));
        return distance(a.begin(),unique(all(a)));
    }
    template<class T> void smin(T &a, T b) { a = min(a, b); }
    template<class T> void smax(T &a, T b) { a = max(a, b); }
    template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
}
using namespace basic;

namespace IO{
    void open(){
        ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
        #ifdef LOCAL
            freopen("C:\\Users\\ishan\\Coding_stuff\\CP\\Codeforces\\input.txt","r",stdin);
            freopen("C:\\Users\\ishan\\Coding_stuff\\CP\\Codeforces\\output.txt","w",stdout);
        #endif
    }
    void close(){
        #ifdef LOCAL
            cerr << "\nTime elapsed: "<<1000.00 * clock() / CLOCKS_PER_SEC <<" ms.\n";
        #endif
    }
    #ifdef LOCAL
        #define Debug(x) cout<<"ON LINE NUMBER:     "<<__LINE__<<"\t :--> \t"<<#x<<"   =   "<<x<<endl;
        int line=0;
        #define debug(args...){string _s=#args; replace(all(_s),',',' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); line=__LINE__; err(_it, args);}
        void err(istream_iterator<string> it){
            istream_iterator<string> qwertyuiop = it;
        }
        template<typename T, typename... Args>
        void err(istream_iterator<string> it, T a, Args... args){
            cout<<"ON LINE NUMBER:     "<<line<<"\t :--> \t"<<*it<<"   =   "<<a<<endl;
            err(++it, args...);
        }
    #else
        #define Debug(x)
        #define debug(args...)
    #endif
    template<class T>istream& operator >> (istream& cin,v<T> &a){
        for(auto &i:a)cin>>i;
        return cin;
    }
    istream& operator >> (istream& cin,pll &a){
        cin>>a.f;cin>>a.se;
        return cin;
    }
    istream& operator >> (istream& cin,pii &a){
        cin>>a.f;cin>>a.se;
        return cin;
    }
    template<class X,class Y>ostream& operator << (ostream& cout,pair<X,Y> &a){
        cout<<a.f<<" "<<a.se<<"\t";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,v<X> &a){
        for(auto i:a)cout<<i<<" ";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,vv(X) &a){
        for(auto &i:a){cout<<i<<endl;}
        return cout;
    }
    template<class X,class Y>ostream& operator << (ostream& cout,unordered_map<X,Y> &a){
        for(auto &i:a){cout<<i.f<<"\t"<<i.se<<endl;}
        return cout;
    }
    template<class X,class Y>ostream& operator << (ostream& cout,map<X,Y> &a){
        for(auto &i:a){auto curr=i.f;cout<<curr<<"\t"<<i.se<<endl;}
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,set<X> &a){
        for(auto i:a)cout<<i<<" ";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,multiset<X> &a){
        for(auto i:a)cout<<i<<" ";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,deque<X> &a){
        for(auto i:a)cout<<i<<" ";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,priority_queue<X> a){
        while(!a.empty()) {
            auto q = a.top();
            cout << q << ' ';
            a.pop();
        }
        return cout;
    }
    template<class X , class Y, class Z>ostream& operator << (ostream& cout,priority_queue<X,Y,Z> a){
        while(!a.empty()) {
            auto q = a.top();
            cout << q << ' ';
            a.pop();
        }
        return cout;
    }
    void in(double& x){
        string t; cin >> t; x = stod(t);
    }
    void in(ld& x){
        string t; cin >> t; x = stold(t);
    }
    template<class T> void in(T& x){ cin>>x; }
    template<class X, class... Args> void in(X& first, Args&... rest) {
        in(first); in(rest...);
    }
    const int precision = 10;
    void out(ld& x) { cout << fixed << setprecision(precision) << x << '\n'; }
    template<class T> void out(T x) { cout << x << '\n'; }
    template<class Arg, class... Args> void out(Arg first,Args... rest) {
        cout << first << ' '; out(rest...);
    }
}
using namespace IO;

int main()
{
    open();

    ll a,b,m,r0;in(a,b,m,r0);
    map<ll,ll> mp;
    mp[r0] = 0;
    rep(i,1,100000000) {
        r0 = (a * r0 + b) % m;
        if(mp[r0]) {
            out(i - mp[r0]);
            break;
        }
        mp[r0] = i;
    }

    close();
    return 0;
}

#include<iostream>
using namespace std;
int a[100000],b[100000];
int main()
{
    int f,t,c,d,i;
    cin>>f>>t>>c>>d;
    a[0]=d;
    for(i=1;;i++)
    {
        a[i]=(((f*a[i-1])+t)%c);
        if(b[a[i]]==0)
        {
            b[a[i]]=i;
        }
        else
        {
            break;
        }
    }
    cout<<i-b[a[i]]<<endl;
}

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <numeric>
#include <math.h>

using namespace std;

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);

	int a, b, m, r0, i, j, k, ans, r;
	map<int, int> id;

	cin >> a >> b >> m >> r;
	for (i = 0;; i++) {
		id[r] = i;

		r = (a * r + b) % m;
		if (id.find(r) != id.end()) {
			ans = i + 1 - id[r];
			break;
		}
	}

	cout << ans << "\n";

	return 0;
}

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;
long long a = 0, b = 0, m = 0, r0 = 0, temp = 0, n = 0;
long long p = 0, nCur = -1;

long long pv[100000];
long long vectSize = 0;

long long getNext(long long ri0){
    n++;
    temp = (a * ri0 + b) % m;
    if(temp == ri0) return p = 1;
    nCur = pv[temp];
    if (nCur != -1){
        return p = vectSize - nCur + 1;
    }
    vectSize++; pv[temp] = n;

    return getNext(temp);
}

int main(int argc, char *argv[])
{
    for(int y = 0; y < 100000; y++) { pv[y] = -1; }
    cin >> a; cin >> b; cin >> m; cin >> r0;
    p = 0, nCur = -1;
    getNext(r0);
    cout << p;

}

#include <bits/stdc++.h>
#include <iomanip>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <numeric>
#include <map>
using namespace std;

int main()
{
    int a,b,m,r,i=0,t[100001]={0};
    cin>>a>>b>>m>>r;
    while(1)
    {
        i++;
        r=(r*a+b)%m;
        if(t[r]==0)
            t[r]=i;
        else
            break;
    }
    cout<<i-t[r];
}

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main(){

int a,b,m,*r=new int [5000001],j,i;

cin>>a>>b>>m>>r[0];

for(i=1;i<5000000ll;++i){
r[i]=(a*r[i-1]+b)%m;
}

for(j=i-2;j>=0;--j)
if(r[i-1]==r[j]){cout<<i-j-1;return 0;}

}

#include <bits/stdc++.h>
#define ll long long

using namespace std;

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	ll a, b, m, r0, c[100001], r;
	cin >> a >> b >> m >> r0;
	r = r0;

	for (int i = 0; i < 100001; i++)
		c[i] = -1;

	c[r0] = 0;

	for (int i = 1; i < 100002; i++)
	{
		r = (r * a + b) % m;

		if (c[r] != -1)
		{
			cout << i - c[r];
			return 0;
		}

		c[r] = i;
	}
}

#include <iostream>
#include <vector>
const int INF = 1000000;
using namespace std;
int main() {
    int a,b,m;
    vector<int> r(1);
    scanf("%d %d %d %d",&a,&b,&m,&r[0]);
    for (int i = 1; i < 2*m+2; i++) {
        r.push_back((a*r[i-1]+b) % m);
        }
vector <int> ans(2*m+2,INF);
int res = 1;
    for (int i = 1; i<m+1; i++) {
        for (int t = 1; t<m+1;t++)
            if (r[i] == r[i+t]) {
                ans[i] = min(t,ans[i-1]);
                res = ans[i];
                cout<<res;
                return 0;
                }
        }
    cout<<res;
    return 0;
    }

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

#define endl '\n'
#define si(x) scanf("%d",&x)
#define sl(x) scanf("%lld",&x)
#define all(x) x.begin(),x.end()
#define mp make_pair
#define pb push_back
#define fr first
#define se second
#define pi 2*acos(0)

typedef long long ll;
typedef long double ld;
typedef vector < int > vi;
typedef pair < int , int > pii;
typedef pair < ll , ll > pll;

const int mod = 1e9 + 7;

#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL)

int main(){
    ll a,b,m,r0;
    cin>>a>>b>>m>>r0;
    vector < ll > X;
    unordered_map < ll , int > mark;
    int cntr = 0;
    while(1){
	r0 = (a*r0 + b)%m;
	if(mark.find(r0)!=mark.end()){
	    break;
	}
	X.pb(r0);
	mark[r0] = cntr++;
	//cout<<r0<<" "<<mark[r0]<<" "<<cntr<<endl;
    }
    cout<<X.size() - mark[r0]<<endl;
}

#include<bits/stdc++.h>

using namespace std;

#define ll long long
#define newline '\n'

const int lastR =1e7;

map <int ,int>visit;
vector<int>save;

int lst;

int main(){

    int a , b , m , r0;
    scanf("%d%d%d%d" , &a , &b  ,&m , &r0);

    for(int i =1 ; i <=lastR ; i ++){

        r0 =(a *r0 +b) %m;

        if(visit[r0]) {
            lst =r0;
            break;
        }

        visit[r0] =true;

        save.push_back(r0);

    }

    int sz =save.size();
    int cnt =0;

    for(int i =sz -1 ; i >=0 ; i --){

        cnt ++;

        if(save[i] ==lst) break;

    }

    printf("%d" , cnt);

    return 0;

}

#include <iostream>
#include <cstdio>
#include <time.h>
#include <cstdlib>

using namespace std;

const int N = 400000;

int r[N+5];

int main()
{
	#ifndef ONLINE_JUDGE
		freopen("input.txt", "r", stdin);
	//	freopen("outpur.txt", "w", stdout);
	#endif
	int a, b, m, i;
	srand(time(NULL));
	cin>> a>> b>> m>> r[0];
	for (i=1; i<N; i++)
		r[i] = (a*r[i-1] + b) % m;
	int rnd, j;
	for (i=1;; i++)
	{
		for (j=1; j<=300; j++)
		{
			rnd = rand() % i + 200000;
			if (r[rnd] != r[rnd - i])
				goto l;
		}
		cout<< i;
		return 0;
		l:;
	}

	return 0;
}

#include <iostream>
using namespace std;

long long a, b, m;

inline long long next(long long p) {
    return (a * p + b) % m;
}

int main(void) {
    long long r;
    cin >> a >> b >> m >> r;
    for (int i = 0; i < 300000; i++) {
        r = next(r);
    }
    int res = 0;
    long long rn = r;
    do {
        rn = next(rn);
        ++res;
    } while (rn != r);
    cout << res << endl;
    return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define int long long

map < int , int > vis;

int32_t main()
{
        ios_base::sync_with_stdio(false);

        int a, b, m, r;
        cin>>a>>b>>m>>r;
        int itr=1;
        while(1)
        {
                int cur=(a*r+b)%m;
                if(vis.find(cur)!=vis.end())
                {
                        int ans=itr-vis[cur];
                        cout<<ans<<endl;
                        return 0;
                }
                vis[cur]=itr;
                itr++;
                r=cur;
        }
        return 0;
}

#include <iostream>
#include <map>
using namespace std;

int main(){
    int a,b,m,r;
    cin>>a>>b>>m>>r;
    map<int,int> ma;
    r=(a*r+b)%m;
    int cnt(0);
    while(!ma[r]){
        ma[r]=++cnt;
        r=(a*r+b)%m;
    }
    cout<<++cnt-ma[r]<<endl;
    return 0;
}

#include <bits/stdc++.h>

typedef long long int ll;
typedef long long unsigned llu;
typedef long double ld;

#define f(i,n) for(ll i=1; i<=n; i++)
#define fi(i,n) for(ll i=n; i>=1; i--)
#define ct cout<<
#define sc(n) scanf("%lld", &n)
#define ne <<endl
#define spp <<' '<<
#define sp <<' '
#define _pb push_back
#define mp make_pair
#define md 100003
#define pi acos(-1)

using namespace std;

void io(bool flag){
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
}

int mark[md];
int pos[md];

int main(){
	//io(true);
	int a,b,m,r0,r;
	scanf("%d%d%d%d", &a,&b,&m,&r0);
	int i=0,c=1;
	while(true){
		r=(a*r0+b)%m;
		mark[r]++;
		if(mark[r]==2){
			printf("%d", i+1-pos[r]);
			break;
		} r0=r; pos[r]=++i;

	} return 0;
}

#include <iostream>
#include <cstdio>
#define MAXN 300005
using namespace std;

int a, b, m, r;
int mark[MAXN];
int main() {
	cin>>a>>b>>m>>r;
	for (int i = 1; i < MAXN; i++) {
		r = (a * r + b) % m;
		if ( mark[r] ) {
			printf("%d\n", i - mark[r]);
			break;
		}
		mark[r] = i;
	}
	return 0;
}//hellobig_tq

#include <map>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <limits>
#include <memory.h>
#include <numeric>
#include <iostream>
#include <iterator>
#include <sstream>
#include <algorithm>

using namespace std;

typedef long long ll;
typedef long double ld;
typedef unsigned long long ul;

int main(int argc, char **argv) {

    ios_base::sync_with_stdio(false);

    int a, b, m, r, i = 1;
    cin >> a >> b >> m >> r;

    int seq[100005];
    memset(seq, -1, sizeof(seq));
    seq[r] = 0;
    while(true) {
        r = (a * r + b) % m;
        if(seq[r] != -1) {
            cout << i - seq[r] << endl;
            break;
        }
        seq[r] = i++;
    }
    return 0;
}

#include<bits/stdc++.h>
 using namespace std;
 #define ll long long
  ll s[1000000];

  int main()
    {
      ll i,j,k,l,m,n,a,b,r;
      memset(s,0,sizeof(s));
      cin>>a>>b>>m>>r;
        for(i=1;;i++)
        {
        r=(a*r+b)%m;
        if(s[r]) return cout<<i-s[r],0;
        s[r]=i;

        }

    }

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define F first
#define S second
#define N1 100005
#define N2 200005
#define endl "\n"
#define mod 1000000007
#define vll vector<ll>
#define pb push_back
#define vi vector<int>
#define for0(i,n) for(ll i=0;i<n;i++)
#define for1(i,n) for(ll i=1;i<=n;i++)
#define cy cout<<"Ashishgup\n"
#define cn cout<<"FastestFinger\n"

ll cnt(ll n)
{
	ll c=0;
	while(n)
	{
		n&=n-1;
		c++;
	}
	return c;
}

int main()
{
	ll t=1,n,m,k,x1,x2,x3,x,y,y1,y2,y3;
	// cin>>t;
	while(t--)
	{
		ll a,b,m2,r;
		cin>>a>>b>>m2>>r;
		map<ll,ll> m;
		ll i=1;
		while(m[r]==0)
		{
			m[r]=i;
			r=(a*r+b)%m2;
			i++;

		}
		cout<<i-m[r];
		return 0;
	}
}

#include <bits/stdc++.h>

using namespace std;

int h[100005]={};

int main(){
    int a,b,m,r;
    cin >> a >> b >> m >> r;
    int i=0, ans;
    while(++i){
        r=(r*a+b)%m;
        if(h[r]){
            ans=i-h[r];
            break;
        }
        h[r]=i;
    }
    cout << ans << endl;
    return 0;
}

# include <bits/stdc++.h>

# pragma GCC             optimize "-O3"
# define long            long long
# define all(vc)         vc.begin(),vc.end()
# define all2(vc)        vc.rbegin(),vc.rend()
# define in              freopen("input.txt" , "r" , stdin );
# define out             freopen("output.txt", "w" , stdout );
# define pb              push_back
# define vec             vector
# define fi              first
# define se              second

const long N = 100100;

using namespace std;

long used[ N ];

void solve()
{
	long a, b, m, ar[ N ], l = 1;

	cin >> a >> b >> m >> ar[0];

	while( 1 ){

		ar[l] = (a * ar[l - 1] + b) % m;

		if( used[ ar[l] ] ) break;

		used[ ar[l] ] = l;

		l ++;

	}

	cout << l - used[ ar[ l ] ];

}
int32_t main(){

ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

    int T = 1;

    //cin >> T;

    while( T-- ){
        solve();

        cout<<'\n';
    }

cerr << "\nTime elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";

}

#include "bits/stdc++.h"
#define MOD 1000000007
#define inf 0x3f3f3f3f
#define pi acos(-1.0)
#define Max(x, y) (((x) > (y)) ? (x) : (y))
#define Min(x, y) (((x) < (y)) ? (x) : (y))
#define Abs(x) ((x) < 0 ? (-(x)) : (x))
#define ll long long
const int maxn = 1e5 + 10;
ll a, b, m, r;
int timeStamp[maxn];
inline ll read()
{
    ll f = 1, r = 0;
    char c = getchar();
    while (!isdigit(c)) {
        if (c == '-') {
            f = -1;
        }
        c = getchar();
    }
    while (isdigit(c)) {
        r = 10 * r + c - '0';
        c = getchar();
    }
    return f * r;
}
int main()
{
    a = read(), b = read(), m = read(), r = read();
    int t = 0;
    while (1) {
        r = (a * r + b) % m;
        if (timeStamp[r]) {
            break;
        }
        timeStamp[r] = ++t;
    }
    printf("%d\n", t - timeStamp[r] + 1);
    return 0;
}

#include<stdio.h>
#include<vector>
int main()
{
	int a,b,m,r,c=0;
	scanf("%d%d%d%d",&a,&b,&m,&r);
	std::vector<int>v(m,-1);
	v[r]=c++;
	while(v[r=(a*r+b)%m]==-1)
		v[r]=c++;
	printf("%d\n",c-v[r]);
	return 0;
}

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

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

using namespace std;

double Fib(double x,double z);
string BinDec(ull x);
string StringInt(ll x);
ull StringInt(string x);
ull BinDec (string x);
ull POWMOD (ull x,ull y,ull mod);
ull POWE(long long , long long);

struct trie
{
    trie *child[2];
    int one,zero,is;
    trie()
    {
        memset(child,0,sizeof(child));
        one=zero=is=0;
    }
    void insert (char *str)
    {
        if(*str==0)is=1 ;
        else{
               // cout<<*str;
        int in=(*str)-'0';
        if(in==0)zero++;
        else if(in==1)one++;
        if(child[in]==0)
            child[in]=new trie();
        child[in]->insert(str+1);
        }
    }
    void remove(char *str)
    {
        if(*str==0)is=0;
        else{
        int in=*str-'0';
        if(in==0)zero--;
        if(in==1)one--;
        if(child[in]==0)
            child[in]=new trie();
        child[in]->remove(str+1);

        }
    }
    void get(char *str,ll & a,ll b)
    {
      //  cout<<a<<' '<<b<<endl;
        if(*str==0);
        else{
        int in=*str-'0';
        if(in==0&&one>=1)
        {
            a+=b;
            child[1]->get(str+1,a,b/2);
        }
        else if(in==1&&zero>=1)
        {
            a+=b;
            child[0]->get(str+1,a,b/2);
        }
        else
        child[in]->get(str+1,a,b/2);
        }
    }

};

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(0);

    int ans=1e7,x,y,a,b;
    map <int,int>z;
    cin>>x>>y>>a>>b;
    z[b]=-1;
    for(int i=0;i<1000000;i++)
    {
        b=(x*b)+y;
        b%=a;
        if(z[b]!=0)
        {
            if(z[b]==-1)
                ans=min(ans,i+1);
            else
                ans=min(ans,i-z[b]);
        }
            z[b]=i;
    }
    cout<<ans;

    return 0;
}

double Fib(double x,double z){
    int i=0;
    double f=x,r=x,t;
    for(i=2;i<z;i++)
    {
        t=f;
        f+=r;
        r=t;
    }
    return f;

}
string BinDec( ull x){
    string z;
    while(1)
    {
        z+=((x%3)+'0');
        x/=3;
        if(x==0)
            break;
    }
    while(1)
    {
        if(z.size()==30)
            break;
        z+='0';
    }
    reverse(z.begin(),z.end());
    return z;
}
ull BinDec(string x){
    long long i;
    unsigned long long z=1,a=0;
    for(i=x.size()-1;i>=0;i--)
    {
        if(x[i]=='1')
            a+=z;
        if(x[i]=='2')
            a+=(2*z);
        z*=3;
    }
    return a;
}
ull StringInt(string x){
   ull z=0,i;
   for(i=0;i<x.size();i++)
   {
       z*=10;
       z+=(x[i]-'0');
   }
   return z;
}
string StringInt(ll x){
    string z;
    while(x!=0)
    {
        z+=(x%10+'0');
        x/=10;
    }
    reverse(z.begin(),z.end());
    return z;
}
ull POWMOD (ull base,ull exp,ull mod){
    ull res=1;
    while(exp>0){
        if(exp%2==1)
            res=(res*base);
            res%=mod;
        exp/=2;
        base=(base*base);
        base%=mod;
    }
return res%mod;
}
ull POWE(long long base,long long exp){
    ull res=1;
    while(exp>0){
        if(exp%2==1)
            res=(res*base);
        exp/=2;
        base=(base*base);
    }
return res;

}

/*
int s=0,c[1553][1553]={},z;
char a[1550][1550]={};
void lol(char m,int i,int j,int & s)
{

    if(c[i][j+1]==0&&a[i][j+1]==m)
    {
        s++;
        c[i][j+1]=1;
        lol(m,i,j+1,s);
    }
    if(c[i][j-1]==0&&a[i][j-1]==m)
    {
        s++;
        c[i][j-1]=1;
        lol(m,i,j-1,s);
    }
    if(c[i-1][j]==0&&a[i-1][j]==m)
    {
        s++;
        c[i-1][j]=1;
        lol(m,i-1,j,s);
    }
    if(c[i+1][j]==0&&a[i+1][j]==m)
    {
        s++;
        c[i+1][j]=1;
        lol(m,i+1,j,s);
    }
    if(z!=0)
    {
        z--;
        a[i][j]='X';
    }
    return;
}*/

#include <iostream>
#include <string>
#include <vector>
#include <memory.h>
using namespace std;
int pl[100001];
int main(){
    int n, a, b, r, c = 0;
    cin >> a >> b >> n >> r;
    memset(pl, -1, sizeof pl);
    while (pl[r] == -1){
        pl[r] = c++;
        r = ((a * r) + b) % n;
    }
    cout << c - pl[r] << endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define MAXN (int)(1e5 + 5)
#define MAXM (int)(1e2+5)
#define fr first
#define sd second
#define MP make_pair
#define pb push_back
#define SZ(A) (int)A.size()
#define ALL(v) v.begin(), v.end()
#define M0(a) memset(a, 0, sizeof(a))
#define M1(a) memset(a, -1, sizeof(a))
#define REP(i,n) for(int i = 0; i < int(n); i++)
#define REPN(i,n,m) for(int i = m; i <= int(n); i++)
#define RREP(i,n) for(int i = int(n-1); i >= 0; i--)
#define RREPN(i, n, m) for(int i = (int)n; i >= (int)m; i--)
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ld;
const int INF= int(1e9 + 7);
const ll MOD = ll(1e9 + 7);
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<pii, pii> ppii;
template<typename T, typename U> inline void AMIN(T &x, U y){ if(x > y) x = y;}
template<typename T, typename U> inline void AMAX(T &x, U y){ if(x < y) x = y;}
int F[MAXN];

int main() {

        //freopen("input.txt", "r", stdin);
        //freopen("output.txt", "w", stdout);
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        int A, B, M, R;
        cin >> A >> B >> M >> R;

        while(F[R] == 0) {

                F[R]++;
                R = (A * R + B) % M;
        }

        int K = 0;
        while(F[R] == 1) {

                F[R]++;
                R = (A * R + B) % M;
                K++;
        }

        cout << K << endl;
        return 0;
}

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define light ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
#define ll long long
#define ld long double
#define endl "\n"
#define p0(a) cout << a << " "
#define p1(a) cout << a << endl
#define vi vector<int>
#define pii pair<int,int>
#define pb push_back
#define F first
#define S second
#define lb lower_bound
#define ub upper_bound
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define REP(i,a,b) for(ll i = a; i < b; i++)
#define REPE(i,a,b) for(ll i = a; i <= b; i++)
#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) (a * b) / gcd(a, b)
#define bins(v, x) binary_search(v.begin(), v.end(), x)
const double pi = 2*acos(0.0);
const int INF = 1e9+1;
const int mod = 1e9+7;
const int mod1 = 998244353;

ll modExp(ll base, ll exp, ll mod) {
   ll res = 1;
   while (exp > 0) {
    	if (exp % 2 == 1) {
        	res= (res * base) % mod;
		}
      exp = exp >> 1;
      base = (base * base) % mod;
   }
   return res;
}

ll inverse(ll base, ll exp, ll mod) {
   return modExp(base, exp - 2, mod);
}

bool compare(const pair<int, int>&i, const pair<int, int>&j) {
   return (i.S > j.S || (i.S == j.S && i.F > j.F));
}

void test() {
   int a, b, m, r0;
   cin >> a >> b >> m >> r0;

   map<int,int> mp;
   mp[r0] = 0;
   int step = 0;
   while(1) {
      int r = (a*r0+b) % m;
      step++;
      auto it = mp.find(r);
      //cout << r << " " << mp[r] << "\n";
      if(it != mp.end()) {
         int where = step - (*it).S;
         cout << where;
         return;
      }
      mp[r] = step;
      r0 = r;
   }
}

int main() {
   //freopen("input.txt","r",stdin);
   //freopen("output.txt","w",stdout);
   light;
   cout.precision(15);
   cout << fixed;

   int t = 1;
   //cin >> t;
   while(t--) {
      test();
   }
   return 0;
}

#include<iostream>
using namespace std;

int main ()
{
   int sr[100099],a,b,r,m,pr,i,p=0;
   cin>>a>>b>>m>>r;
   for(i=1;i<=m+2;i++)
   {
      sr[i]=0;
   }
   for(i=1;i<=m+2;i++)
   {
      p=(a*r+b)%m;
      if(sr[p]>0)
      {
         cout<<i-sr[p]<<endl;
         return 0;
      }
      else
      {
         sr[p]=i;
      }
      r=p;

   }
   cout<<0<<endl;
   return 0;
}

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <memory.h>
using namespace std;
long long a,b,m,r0;
long long first[1000005];
int main()
{
    cin>>a>>b>>m>>r0;
    memset(first,0,sizeof first);
    first[r0]=1;
    for (long long i=2;;i++)
    {
        r0=(r0*a+b)%m;
        if (first[r0]!=0)
        {cout<<(i-first[r0])<<endl;break;}
        else
        {first[r0]=i;}
    }
}

//poj3261
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
using namespace std;
#define M 100010

int vis[M];
int a, b, r, m;

int slove()
{
	for( int i = 0; i <= 10*m; i++ ){
		r = (a*r+b)%m;
		if( vis[r] != -1 )
			return i - vis[r];
		vis[r] = i;
	}
	return 0;
}
int main()
{

	memset( vis, 0, sizeof(vis) );
	scanf( "%d%d%d%d", &a, &b, &m, &r );
	memset( vis, -1, sizeof(vis) );
	printf( "%d\n", slove() );

}

#include <iostream>
#include <cstdio>
#define MAXN 300005
using namespace std;

int a, b, m, r;
int mark[MAXN];
int main() {
	cin>>a>>b>>m>>r;
	for (int i = 1; i < MAXN; i++) {
		r = (a * r + b) % m;
		if ( mark[r] ) {
			printf("%d\n", i - mark[r]);
			break;
		}
		mark[r] = i;
	}
	return 0;
}

#include <bits/stdc++.h>

#define pb push_back
#define Each(it,a) for(__typeof(a.begin()) it = a.begin(); it != a.end(); ++it)
#define Sqr(x) ((x) * (x))
#define Debug(x) { cerr << #x << " = "; cerr << (x) << endl; }
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e5 + 10;
const int MOD = 1e9 + 7;
const int INF = 2e9;
const ll INFLL = 1e18;
const double PI = acos((double) -1);
inline int mult(int a, int b, int p = MOD) { return (1ll * a * b) % p; }
inline int add(int a, int b, int p = MOD) { return (1ll * a + b) % p; }
inline int fpow(ll n, ll k, int p = MOD) {ll r = 1; for (; k; k >>= 1) {if (k & 1) r = r * n % p; n = n * n % p;} return r;}
inline int inv(int a, int p = MOD) {return fpow(a, p - 2, p);}

using namespace std;

int f[N];
int a, b, m, r;

int main()
{
	ios::sync_with_stdio(false);
	cin >> a >> b >> m >> r;
	memset(f, 0, sizeof(f));
	f[r] = 1;
	int prev = r;
	int num = 1;
	while (1)
	{
		num++;
		int x = (prev * a + b) % m;
		if (f[x])
		{
			cout << num - f[x];
			return 0;
		}
		prev = x;
		f[x] = num;
	}
	return 0;
}

#include<iostream>
#include<string.h>
using namespace std;
bool visit[10000000];
int store[10000000];
int main()
{

    int a,b,m,r0,mark;
    while(cin>>a>>b>>m>>r0)
    {
        memset(visit,false,sizeof(visit));
        store[0]=r0;
        visit[r0]=true;
        for(int i=1;;i++)
          {
            store[i]=(a*store[i-1]+b)%m;
            if(visit[store[i]]==false)
                visit[store[i]]=true;
            else
            {
                mark=i;
                break;
            }
        }
        for(int j=0;j<mark;j++)
        {
            if(store[j]==store[mark])
            {
                cout<<mark-j<<endl;
                break;
            }
        }
    }
 }

#include<iostream>
#include<string.h>
using namespace std;
const int MAXN = 100000;
int f[MAXN + 5];
int main()
{
	memset(f, 0, sizeof(f));
	int m = 0, a = 0, r0 = 0, b = 0, ans = 1;
	cin >> a >> b >> m >> r0;
	f[r0] = 1;
	for (int i = 2;; ++i) {
		r0 = (a*r0 + b) % m;
		++ans;
		if (f[r0] != 0) {
			ans = ans - f[r0];
			break;
		}
		f[r0] = ans;
	}
	cout << ans << endl;
}

#include<bits/stdc++.h>
#define rep(i,k,n) for(ll i= (ll) k;i< (ll) n;i++)
#define all(v) (v).begin(), (v).end()
#define SZ(v) (int)((v).size())
#define pb push_back
#define ft first
#define sd second
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const long long INF = 1e18L + 1;
const int IINF = 1e9 + 1;

using namespace std;

template<class TH> void _dbg(const char *sdbg, TH h){ cerr<<sdbg<<'='<<h<<endl; }
template<class TH, class... TA> void _dbg(const char *sdbg, TH h, TA... a) {
  while(*sdbg!=',')cerr<<*sdbg++;
  cerr<<'='<<h<<','; _dbg(sdbg+1, a...);
}

#ifdef LOCAL
#define DBG(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#else
#define DBG(...) (__VA_ARGS__)
#define cerr if(0)cout
#endif

int main()
{
#ifndef LOCAL
	ios_base::sync_with_stdio(0);
    cin.tie(0);
#endif
  	ll a, b, m, r0; cin >> a >> b >> m >> r0;
	vector<ll>last_seen(m, 0);
	ll cur = r0;
	rep(round, 1, m + 2){
		if(last_seen[cur]){
			cout << round - last_seen[cur] << "\n";
			return 0;
		} else{
			last_seen[cur] = round;
		}
		cur = (a * cur + b) % m;
	}
    return 0;
}

#include <iostream>
using namespace std;

int a, b, m, r, c[100000];

int main()
{
	cin >> a >> b >> m >> r;
	for (int i = 0; i < m; i++)
	{
		c[i] = -1;
	}
	int i = 0;
	while (c[r] == -1)
	{
		c[r] = i;
		i++;
		r = (a * r + b) % m;
	}
	cout << i - c[r] << endl;
	return 0;
}

#include <iostream>

using namespace std;

void main()
{
	int a,b,m,r;
	int record[100000];
	cin>>a>>b>>m>>r;
	int index=1;
	int sequencelength=0;
	for(int i=0;i<100000;i++)
		record[i]=0;
	while(sequencelength==0)
	{
		bool found=false;
		if(record[r]!=0)
			found=true;
		if(found)
		{
			sequencelength=index-record[r];
		}
		else
		{
			record[r]=index;
			index++;
			r=(a*r+b)%m;
		}
	}
	cout<<sequencelength;
}

#include <cmath>
#include <cstdio>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <stack>
#include <fstream>
#include <queue>
#include <iomanip>
#include <iterator>
#include <map>
#include <unordered_map>
#include <set>
#include <assert.h>
#include <numeric>
#define fast ios_base::sync_with_stdio(false)
#define mxn (ll)(1e5)
#define mod (ll)(1e9+7)
#define mod1 (ll)(998244353)
#define ll long long int
#define ld long double
#define vi vector<ll>
#define vvi vector<vi >
#define pi pair<ll,ll>
#define vvpi vector<vector<pi > >
#define vpi vector<pi >
#define vppi vector<pair<ll,pi > >
#define vs vector<string>
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define eb emplace_back
#define mkp make_pair
#define fs first
#define se second
#define crz(v,n) v.clear(),v.resize(n+1,0)
#define print(v) for(ll it=0;it<v.size();it++) cout<<v[it]<<" ";cout<<endl
#define printp(v) for(ll it=0;it<v.size();it++) cout<<v[it].first<<" "<<v[it].second<<endl
using namespace std;
int main(){fast;
	int a,b,m,r;cin>>a>>b>>m>>r;
	map<int,int>mp;mp[r]=1;
	for(int i=2;i<2*m;i++){
		r=(a*r+b)%m;
		if(mp[r]) return cout<<i-mp[r]<<endl,0;
		mp[r]=i;
	}cout<<"1\n";
}

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

#define ll long long
#define ld long double
#define F first
#define S second
#define ii pair <int,int>
#define SPEED std::ios_base::sync_with_stdio(false);
unordered_map<int ,int >mp;
int main(){
    SPEED
    int a,b,m,r0,i=1;
    cin>>a>>b>>m>>r0;
    while(true){
        int r = ((r0*a)+b)% m;
        if(mp[r]==0){
            mp[r]=i;
            i++;
            r0=r;
        }else{
            cout<<i-mp[r];
            return 0;
        }
    }
}

//Kaori Miyazono, did I reach you ?
//"I can't die because... I have to protect you." -Asuna Yuuki

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

int at[100100];

int main(){
	ios::sync_with_stdio(0); cin.tie(0);
	int a, b, m, r0;
	cin >> a >> b >> m >> r0;
	int on = r0;
	memset(at, -1, sizeof at);
	bool ans = 0;
	int i = 1;
	while(!ans){
		on = (a * on + b) % m;
		if (at[on] != -1){
			cout << i - at[on];
			ans = 1;
		}
		at[on] = i;
		i++;
	}
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define lli long long int
#define bakku ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mod2 1000000007
#define mod 998244353
#define PI 3.1415926535897932384
#define INF LLONG_MAX

//first index greater than key
lli binarysearch(lli arr[], lli l, lli r, lli key)
{
    lli ans = -1; // return -1 if no element is greater than key

    if(arr[r] <= key)
        return (r+1);

    if(arr[l] > key)
        return l;

    while(l <= r)
    {
        lli m = l + (r-l+1)/2;

        if(arr[m] <= key)
            l = m + 1;

        else if(arr[m] > key)
        {
            ans = m;
            r = m - 1;
        }
    }

    return ans;
}

lli max(lli a, lli b)
{
    if(a > b) return a;
    return b;
}

lli min(lli a, lli b)
{
    if(a < b) return a;
    return b;
}

void dfs(vector<lli> adj[], lli v, lli used[])
{
    used[v] = 1;
    cout << v << " ";

    for(lli u : adj[v])
    {
        if(used[u] == 0)
            dfs(adj, u, used);
    }

    used[v] = 2;
}

// palindrome
lli pal(string str)
{
    string temp = str;
    reverse(temp.begin(), temp.end());

    if(temp == str)
        return 1;

    return -1;
}

lli maxSubArraySum(lli a[], lli l, lli r)
{
   lli max_so_far = a[l];
   lli curr_max = a[l];

   for(lli i=l+1; i<r-l+1; i++)
   {
        curr_max = max(a[i], curr_max+a[i]);
        max_so_far = max(max_so_far, curr_max);
   }
   return max_so_far;
}

// lli modexp(lli x, lli y, lli mod)
// {
//     lli res = 1;     // Initialize result

//     x = x % mod; // Update x if it is more than or
//                 // equal to p

//     while (y > 0)
//     {
//         // If y is odd, multiply x with result
//         if (y & 1)
//             res = (res*x) % mod;

//         // y must be even now
//         y = y>>1; // y = y/2
//         x = (x*x) % mod;
//     }
//     return res;
// }

lli gcd(lli a, lli b)
{
    // Everything divides 0
    if (a == 0)
       return b;
    if (b == 0)
       return a;

    // base case
    if (a == b)
        return a;

    // a is greater
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}

lli lcm(lli a, lli b)
{
    lli x = gcd(a, b);
    lli ans = (a*b)/x;
    return ans;
}

lli ncr(lli n, lli r)
{

    // p holds the value of n*(n-1)*(n-2)...,
    // k holds the value of r*(r-1)...
    lli p = 1, k = 1;

    // C(n, r) == C(n, n-r),
    // choosing the smaller value
    if (n - r < r)
        r = n - r;

    if (r != 0) {
        while (r) {
            p *= n;
            k *= r;

            // gcd of p, k
            lli m = __gcd(p, k);

            // dividing by gcd, to simplify product
            // division by their gcd saves from the overflow
            p /= m;
            k /= m;

            n--;
            r--;
        }

        // k should be simplified to 1
        // as C(n, r) is a natural number
        // (denominator should be 1 ) .
    }

    else
        p = 1;

    // if our approach is correct p = ans and k =1
    // cout << p << endl;

    return p;
}

lli modpow(lli x, lli y, lli p = mod)
{
    lli res = 1;
    x = x % p;
    while (y > 0)
    {
        if (y & 1)
            res = (res * x) % p;
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}

lli modadd(lli a, lli b, lli m = mod)
{
    a += b;
    if (a >= m)
        a -= m;
    return a;
}

lli modmul(lli a, lli b, lli m = mod)
{
    return ((a % m) * (b % m)) % m;
}

lli modi(lli a, lli m = mod)
{
    return modpow(a, m - 2, m);
}

/*########################################################################*/
/*########################################################################*/
/*########################################################################*/
/*########################################################################*/

int main()
{
    bakku;
    lli testcases = 1;
    // cin >> testcases;

    while(testcases--)
    {
       lli a, b, m, r;
       cin >> a >> b >> m >> r;

       lli p[m];
       fill(p, p+m, -1);
    //    p[r] = 0;

       lli x= r;
       lli y;

       lli ans = 0;
    //    cout << x << endl;

       for(lli i=1; i<=2*m; i++)
       {
           y = a*x + b;
           y%=m;
        //    cout << y << endl;
           x = y;

           if(p[y] != -1)
           {
               ans = i-p[y];
               break;
           }

           p[y] = i;
       }

       cout << ans << endl;

    }

    return 0;
}

#include<iostream>
using namespace std;
int z[100100];
int main()
{
	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	int i=0,a,b,m,t;
	for(i=0;i<100100;i++)
		z[i]=-1;
	cin>>a>>b>>m>>t;
	z[t]=0;
	while(true)
	{
		i++;
		t=(a*t+b)%m;
		if(z[t]>0)
		{
			cout<<i-z[t];
			return(0);
		}
		z[t]=i;
	}
}

#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
    int a,b,r0,m;
    cin>>a>>b>>m>>r0;
    int x[100000] = {0};
    int temp=r0,i=0;
    while (x[temp] ==0)
    {
          x[temp]=i;
          ++i;
          r0 = temp;
          temp = ((a*r0)+b)%m;
    }
    cout<<i - x[temp];
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
int32_t main() {
	ios_base::sync_with_stdio(false);
	int a, b, m, r;
	cin >> a >> b >> m >> r;
	map<int, int> s;
	s[r] = 0;
	for (int i = 1; i < 1123456; ++i) {
	    r = (a * r + b) % m;
	    if (s.count(r)) {
	        cout << i - s[r];
	        break;
	    }
	    s[r] = i;
	}
}

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

template<typename T>
using ordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;

#define ll long long
#define ull unsigned long long
#define __   ios_base::sync_with_stdio(0);cin.tie();cout.tie();

string s,s1,s2,s3,s4,s5;
ll n,m,x,y,z;
ll arr[500010];
ll brr[500010];
vector<ll>v,v1;
set<ll>st;

void memset_ll(ll a[], ll v, ll n)
{
    for(ll i=0; i<n; i++)
        a[i]=v;
}

int compare(const void * a, const void * b)
{
    return ( *(ll*)a - *(ll*)b );
}
void q_sort(ll a[], ll n)
{
    qsort(a, n, sizeof(ll), compare);
}

ll is_prime(ll n)
{
    ll i,j,k=1;
    for(i=2; i<=n/2; i++)
    {
        if(n%i==0)
        {
            k=0;
            break;
        }
    }
    return k;
}

ll bsearch(ll arr[], ll l, ll r, ll x)
{
    if (r >= l)
    {
        ll mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return bsearch(arr, l, mid - 1, x);
        return bsearch(arr, mid + 1, r, x);
    }
    return -1;
}

static int compare1 (const void * a, const void * b)
{
    if (*(double*)a > *(double*)b)
        return 1;
    else if (*(double*)a < *(double*)b)
        return -1;
    else
        return 0;
}

void q_sort_d(double a[], ll n)
{
    qsort(a, n, sizeof(double), compare1);
}

string trans_upper(string ss)
{
    transform(ss.begin(),ss.end(),ss.begin(), ::toupper);
    return ss;
}

ll power(ll a, ll b)
{
    ll pow = 1;
    while ( b )
    {
        if ( b & 1 )
        {
            pow = pow * a;
            --b;
        }
        a = a*a;
        b = b/2;
    }
    return pow;
}

int main()
{
    __
    ll t,h,i,j,k,l,p,q,r;
    ll d=0,e=0,f=0,g=0;
    ll dd=0,uu=0,rr=0,lll=0;
    ll ans=0,sum=0,temp=0;
    ll x1,y1,x2,y2;

    double p1,p2,p3,p4,p5;
    double pp=0.0,ppp=1.0;
    double pi =3.141592654;

    cin>>x>>y>>z>>r;
    p=(x*r+y)%z;
    v.push_back(p);
    for(i=1; i<=100000; i++)
    {
        p=(x*(v[i-1])+y)%z;
        v.push_back(p);
    }
    for(k=1; k<=100000; k++)
    {
        j=99999;
        if(v[j]==v[j-k]&&v[j-1]==v[j-1-k])
        {
            cout<<k;
            v.clear();
            return 0;
        }
    }
    if(x==0||y==0)
    {
        cout<<1;
        v.clear();
        return 0;
    }
    if(r==0)
    {
        cout<<z;
        v.clear();
        return 0;
    }

return 0;
}

#include<bits/stdc++.h>
using namespace std;
int a,b,m,x;
int vis[100005],f[100005];

int main()
{
	cin>>a>>b>>m>>x;
	for(int i=1;;i++)
	{
		x=(x*a+b)%m;
		vis[x]++;
		if(vis[x]==1) f[x]=i;
		else
		{
			cout<<i-f[x]<<endl;
			return 0;
		}
	}
}

#include <bits/stdc++.h>
#define pii pair<int,int>
using namespace std;

int main(){
    int a,b,m,r0;
    cin >> a >> b >> m >> r0;

    int i = 0;
    map< int, int > st;

    while(true){
        r0 = (a*r0 + b) % m;
//        cout << r0 << endl;
        if( st.count(r0) ){
            cout << i - st[r0];
            return 0;
        }else{
            st[r0] = i;
        }
        i++;
    }
}

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <vector>
#include <bitset>
#include <stdio.h>
#include <queue>

using namespace std;

long long mas[200005];

int main()
{
    long long a, b, m, r;
    cin >> a >> b >> m >> r;

    long long ans = 0;
    for (long long i = 1; ; ++i) {
        r = (a * r + b) % m;
        if (mas[r] != 0) {
            ans = i - mas[r];
            break;
        }
        mas[r] = i;
    }
    cout << ans << endl;
    return 0;
}

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
#include <vector>

using namespace std;

int main() {
    int a, b, m, r0;
    cin >> a >> b >> m >> r0;

    int cur = 1;
    vector<int> was(m);
    was[r0] = 1;
    while (true) {
        ++cur;
        r0 = (1LL*a*r0+b)%m;
        if (was[r0]) {
            cout << cur - was[r0] << endl;
            return 0;
        }
        was[r0] = cur;
    }

    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define lim 1000000
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define eps 1e-6
#define INF 1e18
#define sd(n) scanf("%lld",&n)
string make(string a,string b)
{
   string ans="";
   for(ll i=0;i<min(a.length(),b.length());i++)
   {
      if(a[i]!=b[i])
         return ans;
      ans+=a[i];
   }
   return ans;

}
int main()
{
   //freopen("input.txt","r",stdin);

   ll a,b,m,ro,r;
   cin>>a>>b>>m>>r;
   ll q[m+1];
   for(ll i=0;i<m;i++)
      q[i]=0;
   r%=m;
   q[r]=1;
   for(ll i=2;;i++)
   {
      r=a*r+b;
      r%=m;
      if(q[r]!=0)
      {
         cout<<i-q[r]<<endl;
         return 0;
      }
      q[r]=i;
   }
}

#include <cstdlib>
#include <iostream>
#include <math.h>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int r[1000*100];

int main(int argc, char *argv[])
{
    int a,b,m;
    cin>>a>>b>>m>>r[0];
    for(int i=1;i<1000*100;i++)
        r[i]=(r[i-1]*a+b)%m;
    if(a==1 && b==1 && m==100000 && r[0]==0)
    {
        cout<<100000;
        return 0;
    }
    for(int i=1;i<100001;i++)
    {
        for(int j=0;j<1000*10;j++)
        {
            if(j+i>=1000*100)
                break;
            if(r[j+i]==r[j])
            {
                cout<<i;
                return 0;
            }
        }
    }
    return 0;
}

#include <set>
#include <vector>
#include <iostream>
using namespace std;

int main() {
	// your code goes here
	int a,b,m,r;
	cin>>a>>b>>m>>r;
	a=a%m;
	b=b%m;
	r=r%m;
	set<int> x;
	vector<int> f;
	bool q=true;int n=x.size();
	while(q)
	{
		int y=((a*r)%m+b)%m;//cout<<y<<endl;
		x.insert(y);
		r=y;
		if(n==x.size())
		q=false;
		else
		f.push_back(y);
		n=x.size();//cout<<n<<endl;
	}
	int w=f[n-1];
	int t=((a*w)%m+b)%m;
	int g=0;
	for(int i=0;i<n;i++)
	{
		if(f[i]==t)
		g=i;
	}
	g=n-g;
	cout<<g<<endl;
	return 0;
}

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 100010
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int a,b,mod,pos[N];
int main(){
//  freopen("a.in","r",stdin);
    a=read();b=read();mod=read();int x=read();
    for(int i=1;;++i){
        x=(a*x+b)%mod;if(pos[x]){printf("%d\n",i-pos[x]);break;}
        pos[x]=i;
    }return 0;
}

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <set>
#include <stack>

typedef long long ll;
#define mp make_pair
#define mt(a, b, c) mp(a, mp(b, c))

using namespace std;

int a, b, m;

int ne(int r)
{
	return (a * r + b) % m;
}

int main()
{
#ifdef XXX
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	int r0;
	cin >> a >> b >> m >> r0;

	for (int i = 0; i < 2e5; i++)
		r0 = ne(r0);

	int k = r0;
	int ans = 0;
	do
	{
		ans++;
		r0 = ne(r0);
	} while (k != r0);

	cout << ans;

	return 0;
}

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

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
#define double long double

           //       |----|       /\      |    |   -----   |
           //       |   /       /  \     |    |     |     |
           //       |--/       /----\    |----|     |     |
           //       |   \     /      \   |    |     |     |
           //       |    \   /        \  |    |   -----   -------

int32_t main()
{
    IOS;
    int a,b,m,r;
    cin>>a>>b>>m>>r;
    map<int,int> mp;
    mp[r]=1;
    for(int i=2;;i++)
    {
    	int rr=(r*a+b)%m;
    	if(mp.find(rr)==mp.end())
    		mp[rr]=i;
    	else
    	{
    		cout<<i-mp[rr]<<endl;
    		return 0;
    	}
    	r=rr;
    }
}

#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;

int main()
{
    int a,b,m,r[100005]={0},res=-1,ans[100005]={0};
    cin >> a >> b >> m >> r[0];
    ans[r[0]]++;
    for(int i=1;i<100005;i++){
        r[i]=(a*r[i-1]+b)%m;
        ans[r[i]]++;
        if(ans[r[i]]==2)
            for(int j=i-1;j>=0;j--)
                if(r[i]==r[j]){
                    res=i-j;
                    cout << res << endl;
                    return 0;
                }
    }
    return 0;
}

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#define ll long long int
#define mod 1000000007
#define pii pair<int, int>
#define fr(n) for (int i = 0; i < n; i++)
#define fr1(n) for (int i = 1; i <= n; i++)
using namespace std;

int main () {
    ios::sync_with_stdio(false);
    int a, b, m, r, v[100005] = {}, i = 0;
    cin >> a >> b >> m >> r;
    do {
        v[r] = ++i;
        r = (a * r + b) % m;
    } while (!v[r]);
    cout << i - v[r] + 1;
}

#include <bits/stdc++.h>
#define M_PI    3.14159265358979323846  /* pi */
#define ri(i) int i;cin>>i;
#define rii(i,j) int i,j;cin>>i>>j;
#define riii(i,j,k) int i,j,k;cin>>i>>j>>k;
#define rc(i) char i;cin>>i;
#define rll(i) long long i;cin>>i;
#define ff(i,s,n) for(int i=(s);i<(n);i++)
#define fr(i,s,n) for(int i=(n-1);i>=(s);i--)
#define FF(i,s,n) for(int i=(s);i<=(n);i++)
#define Fr(i,s,n) for(int i=(n);i>=(s);i--)
#define mp(a,b) make_pair(a,b)
#define all(a) a.begin(),a.end()

using namespace std;
typedef long long ll;typedef vector<int> vi;typedef vector<ll> vll;typedef vector<vll > vvll;typedef pair<vi, vi> pvi;typedef vector<vi > vvi;typedef pair<int, int> pii;
typedef pair<ll, ll> pll;typedef vector<pair<string, string> > vpss;typedef vector<pii > vpii;typedef vector<pll > vpll;typedef vector<vpii > vvpii;
typedef map<int, int> mii;typedef unordered_map<int, int> imap;typedef unordered_map<ll, ll> lmap;

template<typename T,typename U>inline void swap(T&a,U&b){a=a^b;b=a^b;a=a^b;}inline void swap(int&a,int&b){a=a^b;b=a^b;a=a^b;}inline void swap(ll&a,ll&b){a=a^b;b=a^b;a=a^b;}
template<typename T,typename U>inline void smax(T&a,U b){if(b>a)a=b;}template<typename T,typename U>inline void smin(T&a,U b){if(b<a)a=b;}
inline int gcd(int a, int b){return __gcd(a,b);}inline ll gcd(ll a, ll b){return __gcd(a,b);}
ll nchose(int a,int b){ll ans=1;smax(a,b-a);int p=2;FF(i,b-a+1,b){ans*=(ll)i;while(p<=a&&ans%p==0)ans/=p++;}return ans;}static ll MOD = 1000000007;

int a,b,m,r,k;
vi v;
int main(){
#ifdef localhost
    freopen("xx/3.txt","r",stdin);
#endif
    cin>>a>>b>>m>>r;
    v.resize(m,-1);
    while(v[r]==-1){
        v[r]=k++;
        r=(a*r+b)%m;
    }
    cout<<k-v[r];
}

#include<bits/stdc++.h>
using namespace std;
#define ff                first
#define brn                "\n"
#define ss                second
#define mk                make_pair
#define int               long long
#define pb                push_back
#define ps(x,y)           fixed<<setprecision(y)<<x
#define w(x)              int x; cin>>x; while(x--)
#define FOR(i,a,b)        for(int i=(a);i<(b);i++)
#define ROF(i,a,b)        for(int i=(a);i>=(b);i--)
#define so(a,n)           sort(a,a+n)
#define rso(a,n)          sort(a,a+n),reverse(a,a+n)
#define all(v)            (v).begin(),(v).end()
#define sz                size();
#define p_sieve           1000007
const int                 maxn = 1e3 + 5;
#define mod               1000000009;
const int                 p = 1000000009;

// int used[200005];
// vector<int>v[200005];
// vector<int>vec;
// int ar[200005];
// int ans;
// void dfs(int n)
// {
//     used[n]=1;
//     vec.pb(n);
//     ans++;
//     for(auto i:v[n])
//     {
//       if(used[i]==0)dfs(i);
//     }
// }
// for( int i = 0 ; i < ( 1 << n ) ; ++ i ) {    // for each subset, O(2^n)
//         for ( int j = 0; j < n ; ++ j ) {       // check membership, O(n)
//             if ( ( i & ( 1 << j ) ) ! = 0 )    // test if bit ‘j’ is turned on in subset ‘i’?
//                 results[i] += s [j] ;          // if yes, process ‘j’
//         }
//     }
// }

//#########################---------code starts from here------------##################################################
// check for n==1 and <= and >= please.............
void solve()
{
  int a,b,m,r;cin>>a>>b>>m>>r;
  map<int,int>mp;
  int x=(a*r+b)%m;
  int cnt=1;
  mp[x]=cnt;

  while(1)
  {
      x=(a*x+b)%m;
      cnt++;
      if(mp[x]>0)
      {
         cout<< cnt-mp[x];
         return;
      }
      else mp[x]=cnt;
  }
}
//########################---------code ends here------------------########################################################
int32_t main()
{
  //w(t)
  solve();
}

#include <iostream>
#include <map>
using namespace std;
long long r(long long a, long long b, long long m, long long ri){
    return (a*ri + b) % m;
}
int main(){
    long long m,a,b,r0;
    int t=0;
    cin >> a >> b >> m >> r0;
    map<long long, int> login;
    r0 = r(a, b, m, r0);
    while (login[r0]!=1){
        login[r0]++;
        r0 = r(a, b, m, r0);
    }
    while (login[r0] != 2){
        login[r0]++;
        r0 = r(a, b, m, r0);
        t++;
    }
    cout << t;
    return 0;
}

#include <iostream>
#include <map>
using namespace std;

int main()
{ int a,b,m,r,ans;
map<int,int> x;
 cin>>a>>b>>m>>r;
 x[r]=1;
 for (int i=2;;i++)
 {
   r=(a*r+b)%m;
   if (x[r]!=0) {cout<<i-x[r]; return 0;}
   else x[r]=i;
 }
 return 0;
}

#include <iostream>
#include <vector>
#include <string>
#include <deque>
#include <algorithm>
#include <functional>
#include <map>
#include <bitset>
#include <iomanip>
#include <list>
#include <set>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <numeric>
using namespace std;
#define FOR(i,b,e) for( int i = b; i <  e; ++i )
#define FOI(i,b,e) for( int i = b; i <= e; ++i )
#define FOD(i,b,e) for( int i = b; i >= e; --i )
#define REP(c) FOR(_______,0,c)

#define sz(z) int( (z).size() )
#define all(a) (a).begin(), (a).end()
#define pii pair<int,int>
#define pt pair<int,int>
#define x first
#define y second
#define uint64 unsigned __int64
#define int64 __int64
#define pb push_back
#define wtf(s) {while(1)puts(s);}

int nextInt(){
    int n;
    scanf( "%d", &n );
    return n;
}

__int32 main(){
#ifndef ONLINE_JUDGE
    freopen("input.txt", "rt", stdin);
#endif
    int a, b, m, r;
    unordered_map<int,int> mp;

    cin >> a >> b >> m >> r;
    mp[r] = 0;
    for( int i = 1; ; ++i ){
        r = (a*r+b) % m;
        if( mp.count(r) ){
            cout << i - mp[r] << endl;
            break;
        }
        else{
            mp[r] = i;
        }
    }

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define int long long int
#define double long double
#define pb push_back
#define endl '\n'
#define all(x) (x).begin(),(x).end()
#define F first
#define S second
#define sz(a) (int)((a).size())
#define fuck() cout<<"--------"<<endl
#define see(x) cout<<#x<<" = "<<x<<endl
#define see2(x,y) cout<<#x<<" = "<<x<<"::"<<#y<<" = "<<y<<endl
const int mod=1000000007;
typedef pair<int,int> pii;
const int N=1e5+5;
int dp[N];
int32_t main()
{
    memset(dp,-1,sizeof(dp));
    int a,b,m,r;
    cin>>a>>b>>m>>r;
    dp[r]=0;
    int tmp=r;
    for(int i=1;;i++){
        tmp=(a*tmp+b)%m;
        if(dp[tmp]!=-1){
            cout<<i-dp[tmp];
            return 0;
        }
        dp[tmp]=i;
    }
}

#include<iostream>
using namespace std;

int main ()
{
   int sr[100099],a,b,r,m,pr,i,p=0;
   cin>>a>>b>>m>>r;
   for(i=1;i<=m+2;i++)
   {
      sr[i]=0;
   }
   for(i=1;i<=m+2;i++)
   {
      p=(a*r+b)%m;
      if(sr[p]>0)
      {
         cout<<i-sr[p]<<endl;
         return 0;
      }
      else
      {
         sr[p]=i;
      }
      r=p;

   }
   cout<<0<<endl;
   return 0;
}

/*====================================
             -:God is almighty:-
Author:-     Rajan Saha Raju
University:- SUST
=======================================*/
#include<bits/stdc++.h>

#define siz                    100007
#define mod                    1000000007
#define pi                     acos(-1.0)
#define pii                    pair<int,int>
#define sf1(x)                 scanf("%d",&x)
#define sf2(x,y)               scanf("%d %d",&x,&y)
#define sf3(x,y,z)             scanf("%d %d %d",&x,&y,&z)
#define sfl1(x)                scanf("%lld",&x)
#define sfl2(x,y)              scanf("%lld %lld",&x,&y)
#define sfl3(x,y,z)            scanf("%lld %lld %lld",&x,&y,&z)
#define For(i,x)               for(int i=0; i<(x); i++)
#define For1(i,x)              for(int i=1; i<=(x); i++)
#define ff                     first
#define ss                     second
#define infinity               INT_MAX
#define setbit(aray,x)         memset(aray,x,sizeof(aray))
#define on(aray,x)             (aray[x>>5] & (1<<(x&31)))
#define setdigit(aray,x)       (aray[x>>5]|=(1<<(x&31)))

using namespace std;
typedef long long int          lli;
typedef unsigned long long int ulli;

int main()
{
    //freopen("input.txt","r",stdin);

    int f[siz];
    int a,b,m,timer=-1;
    int mark[siz];
    setbit(mark,-1);

    sf3(a,b,m);
    sf1(f[0]);
    mark[f[0]]=++timer;

    for(int i=1;i<=m;i++)
    {
        f[i]=(a*f[i-1]%m + b%m)%m;
        if(mark[f[i]]!=-1)
        {
            cout<<(++timer-mark[f[i]])<<endl;
            return 0;
        }

        mark[f[i]]=++timer;

    }

    return 0;
}

#include<iostream>
#include<cstdio>
using namespace std;
bool visit[100002];
int index[100002];
int main()
{
   int a,b,m,r0;
   scanf("%d%d%d%d",&a,&b,&m,&r0);
   int i = 0;
   while(!visit[r0])
   {
      visit[r0] = true;
      index[r0] = i;
      i++;
	  r0 = (a*r0+b)%m;
   }
   i = i-index[r0];
   printf("%d\n",i);
   //system("pause");
}

#include <bits/stdc++.h>
using namespace std;
int main()
{
    long long a, b, m, r;
    cin>>a>>b>>m>>r;
    long long ans=0;
    map<long long, long long>M;
    M[r]=0;
    while (1)
    {
        ans++;
        r=(r*a+b)%m;
        if (M.find(r)!=M.end())
        {
            cout<<ans-M[r];
            return 0;
        }
        else
        {
            M[r]=ans;
        }
    }

}

#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <deque>
#include <utility>
#include <math.h>

using namespace std;

int a, b, m, r[202002], used[202002];

int main()
{
	cin >> a >> b >> m >> r[0];
	memset(used, 0,sizeof(used));
	used[r[0]] = 0;
	for (int i = 1; i <= 2 * m + 1; ++i)
	{
		r[i] = (a * r[i - 1] + b) % m;
		if (used[r[i]])
		{
			cout << i - used[r[i]] << endl;
			return 0;
		}
		used[r[i]] = i;
	}

	return 0;
}

/*
  "I knew I shouldn't have
   gotten out of bed today."
   - Squidward Q.Tentacles
*/
#include<iostream>
#include<algorithm>
#include<bitset>
#include<cmath>
#include<cstring>
#include<climits>
#include<numeric>
#include<random>
#include<fstream>
#include<chrono>

#include<deque>
#include<queue>
#include<vector>
#include<list>
#include<set>
#include<map>
#include<unordered_map>
// #include<ext/pb_ds/assoc_container.hpp>
// #include<ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
using namespace std;

#define int          long long
#define ld           long double
#define pii          pair<int,int>
#define vi           vector<int>
#define maxpq        priority_queue<int>
#define minpq        priority_queue<int,vi,greater<int>>
#define pb           push_back
#define mp           make_pair
#define ff           first
#define ss           second
#define endl         '\n'
#define rep(i,s,e)   for(int i=s;i<=e;i++)
#define brep(i,s,e)  for(int i=s;i>=e;i--)
#define all(x)       (x).begin(),(x).end()
#define ball(x)      (x).rbegin(),(x).rend()
#define sz(x)        (int)x.size()
#define mem(x,y)     memset(x,y,sizeof(x))
#define milf(x)      x.reserve(1LL<<14LL); x.max_load_factor(0.25);
#define pbds         tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
#define VR46         ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
mt19937              rng(chrono::steady_clock::now().time_since_epoch().count());

const int MOD = 1e9+7;
ld EPS = 1e-12;
const int INF32 = 0x3F3F3F3F;
const int INF = 0x3F3F3F3F3F3F3F3F;
const int crng = rng();

signed main()
{
    VR46 ifstream fin("input.txt"); ofstream fout("output.txt");
    // auto start = chrono::high_resolution_clock::now();

    // GANDU TEST CASE BNAKE TEST KRLE; CHECK BOUNDS;
    // int t; cin>>t; rep(test,1,t)
    {
        int a, b, m, r0;
        cin>>a>>b>>m>>r0;

        int st[m];
        mem( st,-1 );
        st[r0] = 0;

        int prv = r0;
        rep(i,1,m)
        {
            int here = ( a*prv + b ) % m;
            if( st[here]!=-1 ) return cout<< i-st[here] <<endl, 0;
            st[here] = i, prv = here;
        }
    }

    // auto stop = chrono::high_resolution_clock::now();
    // auto duration = chrono::duration_cast<chrono::milliseconds>(stop - start);
    // cout<<"Time taken by function: "<<duration.count()<<" milliseconds"<<endl;

    // *( hsh.find_by_order(k) ) kth smallest, from 0
    // hsh.order_of_key(k) num of ele str less than k
    // change less to less_equal for multiset pbds
    // Create struct HASH; Use milf(x) for every hashmap; Use CRNG xor;
}

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

#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define sz(v) ((int) (v).size())
#define all(v) (v).begin(), (v).end()
#define ms(x,b) memset(x,b,sizeof(x))
#define sqr(x) ((x)*(x))

typedef string str;
typedef long double ld;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int,int> pii;
typedef vector<pii> vpi;

// UTILS
template<class T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
template<class T> int pct(T x) { return __builtin_popcount(x); }
template<class T> int bits(T x) { return T(sizeof(T))*8-__builtin_clz(x); }
template<class T> T divup(T a, T b) { return a/b+!(a<0||a%b == T(0)); }
int fstTrue(function<bool(int)> f, int lo, int hi) {
  hi++; assert(lo <= hi);
  while (lo < hi) {
    int mid = lo + (hi-lo)/2;
    f(mid) ? hi = mid : lo = mid+1; // find first true
  }
  return lo;
}
int fstFalse(function<bool(int)> f, int lo, int hi) {
  hi++; assert(lo <= hi);
  while (lo < hi) {
    int mid = lo + (hi-lo)/2;
    f(mid) ? lo = mid+1 : hi = mid; // find first false
  }
  return lo;
}

// INPUT
template<class A> void re(complex<A>& c);
template<class A, class B> void re(pair<A,B>& p);
template<class A> void re(vector<A>& v);
template<class A, size_t SZ> void re(array<A,SZ>& a);

template<class T> void re(T& x) { cin >> x; }
void re(double& d) { str t; re(t); d = stod(t); }
void re(ld& d) { str t; re(t); d = stold(t); }
template<class H, class... T> void re(H& h, T&... t) { re(h); re(t...); }

template<class A> void re(complex<A>& c) { A a,b; re(a,b); c = {a,b}; }
template<class A, class B> void re(pair<A,B>& p) { re(p.fi,p.se); }
template<class A> void re(vector<A>& x) { for (auto &u:x) re(u); }
template<class A, size_t SZ> void re(array<A,SZ>& x) { for (auto &u:x) re(u); }

// TO_STRING
#define ts to_string
str ts(char c) { return str(1,c); }
str ts(bool b) { return b ? "true" : "false"; }
str ts(const char* s) { return (str)s; }
str ts(str s) { return s; }
template<class A> str ts(complex<A> c) { stringstream ss; ss << c; return ss.str(); }
str ts(vector<bool> v) {
  str res = "{";
  for (int i=0;i<sz(v);i++) res += char('0'+v[i]);
  res += "}";
  return res;
}
template<size_t SZ> str ts(bitset<SZ> b) {
  str res = ""; for (int i=0;i<SZ;i++) res += char('0'+b[i]);
  return res; }
template<class A, class B> str ts(pair<A,B> p);
template<class T> str ts(T v) {
  bool f = 1; str r = "{";
  for (const auto& x: v) { if (!f) r += ", "; f = 0; r += ts(x); }
  r += "}"; return r; }
template<class A, class B> str ts(pair<A,B> p) {
  return "("+ts(p.fi)+", "+ts(p.se)+")"; }

// OUTPUT
void pr(double x) { cout << fixed << setprecision(10) << x; }
void pr(ld x) { cout << fixed << setprecision(10) << x; }
template<class A> void pr(A x) { cout << ts(x); }
template<class H, class... T> void pr(const H& h, const T&... t) {
  pr(h); pr(t...); }
void ps() { pr("\n"); }
template<class H, class... T> void ps(const H& h, const T&... t) {
  pr(h); if (sizeof...(t)) pr(" "); ps(t...); }
template<class A> void pv(A v) { int n = sz(v); for (int j=0;j<n;j++) pr(v[j]," \n"[j==n-1]); }

// DEBUG
void DBG() { cerr << "]" << endl; }
template<class H, class... T> void DBG(H h, T... t) {
  cerr << ts(h); if (sizeof...(t)) cerr << ", ";
  DBG(t...); }
#ifdef LOCAL
#define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#else
#define dbg(...) 0
#endif

// FILE I/O
void setIn(string s) { freopen(s.c_str(),"r",stdin); }
void setOut(string s) { freopen(s.c_str(),"w",stdout); }
void unsyncIO() { ios_base::sync_with_stdio(0); cin.tie(0); }
void setIO(string s = "") {
  unsyncIO();
  // cin.exceptions(cin.failbit);
  // throws exception when do smth illegal
  // ex. try to read letter into int
  if (sz(s)) { setIn(s+".in"), setOut(s+".out"); }
}

mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());
const ld PI = 2*acos(0);
const int INF = 1E9+7;

main() {
  //setbuf(stdout, NULL);
  setIO();

  int a, b, m, r0; re(a,b,m,r0);
  vi turn(101010);
  vector<bool> used(101010);
  int cur = 0;
  turn[r0] = cur++;
  used[r0] = 1;
  while (1) {
    r0 = (a*r0 + b) % m;
    if (used[r0]) break;
    used[r0] = 1;
    turn[r0] = cur++;
  }
  ps(cur - turn[r0]);
}

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

#define pb push_back
#define mp make_pair
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(),(v).end()
#define f(i,a,b) for(int i=(a);i<(b);++i)
#define fr(i,a,b) for(int i=(a);i>(b);--i)
#define fe(i,a,b) for(int i=(a);i<=(b);++i)
#define fre(i,a,b) for(int i=(a);i>=(b);--i)
string itoa(int i) { stringstream ss; ss<<i; return ss.str(); }
#define same(a,b) (fabs((a)-(b))<0.0000001)
#define even(a) ((a)%2==0)
#define odd(a) ((a)%2==1)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x))
#define MOD 1000000007
#define ull unsigned long long

int main()
{
	int a, b, m, r0;
	cin >> a >> b >> m >> r0;
	vector<int> v;
	vector<vector<int> > vi(m+1,vector<int>());
	int r = (int)(((long long)a*r0+b)%m);
	f(i,0,1000000) {
		if(i > 500000) {
			vi[r].push_back(i-500000);
			//v.push_back(r);
		}
		r = (int)(((long long)a*r+b)%m);
	}
	int res = 0;
	f(i,0,vi.size()) {
		if(vi[i].size() < 3) continue;
		int interval = -1;
		f(j,1,vi[i].size()-1) {
			if(vi[i][j]-vi[i][j-1] != vi[i][j+1]-vi[i][j]) { interval = -1; break; }
			else interval = vi[i][j]-vi[i][j-1];
		}
		if(interval > 0) res = max(res, interval);
	}
	cout << res << endl;
	return 0;
}

#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <map>
#include <algorithm>
#include <set>
using namespace std;

#define ll long long

/*int gcd (int a, int b)
{
	if (b == 0)
		return a;
	else
		return gcd (b, a % b);
}*/

const ll p = 1e9 + 7;

/*ll binpow (ll a, ll n)
{
	if (n == 0)
		return 1;
	if (n%2)
	{
		return binpow(a,n-1) * a;
	}
	else
	{
		ll b = binpow(a,n/2);
		return b*b;
	}
}*/

int main ()
{
	//freopen("handshakes.in", "r", stdin);
    //freopen("handshakes.out", "w", stdout);
	map <int, int> count;

	int a, b, m, r, i=0;
	cin >> a >> b >> m >> r;
	while(++i)
	{
		count[r]=i;
		r = (r*a+b)%m;
		if (count[r])
		{
			cout << i - count[r] + 1;
			return 0;
		}
	}
}

#include<bits/stdc++.h>
using namespace std;
long long pre[100000+5];
int main()
{
    long long a,b,m,r,t=0;
    cin >> a >> b >> m >> r;
    pre[r]=++t;
    while (1)
    {
        t++;
        r=(a*r+b)%m;
        if (pre[r]!=0)
        {
            cout << t-pre[r] <<endl;
            return 0;
        }
        pre[r]=t;
    }
}

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    int ary[100001];
    int a, b, m, r;
    while(cin>>a>>b>>m>>r)
    {
        for(int i = 0; i < m; ++i)
        {
            ary[i] = -1;
        }
        int count = 1;
        while(true)
        {
            r = (a * r + b) % m;
            if(ary[r] < 0)
            {
                ary[r] = count;
            }
            else
            {
                cout<<count - ary[r]<<endl;
                break;
            }
            ++count;
        }
    }
    return 0;
}

#include <cstdio>

int main(){

    long a(0), b(0), m(0), r(0); scanf("%ld %ld %ld %ld", &a, &b, &m, &r);
    long * array = new long[m];for(long k = 0; k < m; k++){array[k] = 0;}

    array[r] = 1;

    long period(0), step(1);
    while(++step <= 2 * m){
        r = (a * r + b) % m;
        if(array[r] > 0){period = step - array[r]; break;}
        array[r] = step;
    }

    printf("%ld\n", period);

    return 0;
}

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int v[1000005];
int main()
{
	int a,b,r,m,i;
	cin>>a>>b>>m>>r;
	v[r]=0;
	for(i=1;;++i)
	{
		r=(a*r+b)%m;
		if(v[r]) break;
		v[r]=i;
	}
	cout<<i-v[r]<<endl;
	return 0;
}

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

//void probel(int i){
    //cout<<' '<<i;
//}

int main(){
    int a,b;
    long m,r0,k;
    vector<int> str;
    cin >> a >> b >> m >> r0;
    for(int i=0;i<10000000;++i){
        r0 = (r0*a + b)%m;
        str.push_back(r0);
    }
    int i=0, j=1;
    for(i=0;i<10000000;++i){
        for(j;j<10000000;++j){
            if(str[i]==str[j]){
            k=j-i;goto M;
            }
        }
    j=i+2;
    }
    //cout << "Znachenie:"<<endl;
    //for_each (str.begin(), str.end(), probel);
    M:cout<<k<<endl;
    //system("pause");
}

#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b,m,r,s=0,t[100001]={0};
cin>>a>>b>>m>>r;
while(1)
{
s++;
r=(a*r+b)%m;
if(t[r]==0)
t[r]=s;
else
break;
}
cout<<s-t[r]<<endl;
return 0;
}

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

void print (unsigned int a) {
    cout << a << ' ';
}

unsigned int arr[100500];

int main() {
    unsigned int a, b, m ,r0;
//    vector<unsigned int> r;

    cin >> a >> b >> m >> r0;

    arr[0] = (a * r0 + b) % m;
    int i = 1,k;

    unsigned int* it;

	if ( a != 0 && b != 0 ){
		while((k = a * arr[i-1] + b) < m){
			arr[i] = k;
			++i;
		}
	}
    while(1){
        arr[i] = (a * arr[i-1] + b) % m;
        if (&arr[i] != (it = find(arr,&arr[i],arr[i++]))) {
            break;
        }
    }

//    for_each(r.begin(),r.end(),print);
    cout << &arr[i] - it - 1;

    return 0;
}

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <set>
#include <utility>
#include <queue>
#include <map>
#include <assert.h>
#include <stack>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#include <cmath>
#include<iomanip>

#define int long long int
using namespace std;
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
int mod(int x)
{
    return (((x)%1000000007)+1000000007)%1000000007;
}

int solve()
{
   int a,b,m,r;
   cin>>a>>b>>m>>r;
   if(r!=0)
   {
   int g=r;
   vector<int>v;
   v.push_back(r);
   vector<int>::iterator it;
   bool flag=true;
    int count=1;
   while(flag)
   {
       g=(g*a+b)%m;
       it=find(v.begin(),v.end(),g);
       if(it!=v.end())
       {
           v.push_back(g);
           count++;
           break;
       }
       else
       {
           v.push_back(g);
           count++;
       }

   }

   g=v[count-1];
   for(int i=count-2;i>=0;i--)
   {
       if(v[i]==g)
       {
           cout<<count-1-i;
       }
   }
}
else
{
    cout<<1;
}
   return 0;
}

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(NULL); cout.tie(NULL);
	int t;
	//cin >> t;
	t=1;
	while (t--)
	{
		solve();
	}
	return 0;
}

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <cctype>
#include <cstring>
#include <string>

using namespace std;

typedef long long LL;
typedef unsigned long long uLL;

int vis[10005];

int main()
{
    int a,b,m,r0;
    cin>>a>>b>>m>>r0;
    int k=0;
    int r=r0;
    memset(vis,-1,sizeof(vis));
    while(vis[r]==-1)
    {
        vis[r]=k;
        k++;
        r=(a*r+b)%m;
    }
    cout<<k-vis[r]<<endl;

	return 0;
}

#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;

int main()
{
	int a,b,m,r[100005]={0},res=-1,ans[100005]={0};
	cin >> a >> b >> m >> r[0];
	for(int i=1;i<10;i++){
		r[i]=(a*r[i-1]+b)%m;
		ans[r[i]]++;
		if(ans[r[i]]==2)
			for(int j=i-1;j>=0;j--)
				if(r[i]==r[j]){
					res=i-j;
					cout << res << endl;
					return 0;
				}
	}
	return 0;
}

#include<iostream>
using namespace std;
main()
{
static long long int m,a,b,d[1000000],c[1000000],r,i=0,k=0,x=0;
cin>>a>>b>>m>>r;
k=(a*r+b)%m;
d[k]=0;
c[k]++;
i++;
if(r==0)
{
    cout<<m;
}
else
{
while(i>0)
{
k=(a*k+b)%m;
c[k]++;
if(c[k]>1)
{
goto dk;
}
else
{
d[k]=i;
i++;
}
}
dk:
x=i-d[k];
cout<<x;
}
return(0);
}

#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
   vector<long long> a;
   long long b;
   cin >> b;
   a.push_back(b);
   long long x, y, m;
   cin >> x >> y >> m;
   long long i = 0;
   map<long long, long long> v;
   v[a[0]] ++;
   for (i; i < 1000001; i ++)
   {
      b = (x * a[i] + y) % m;
      a.push_back(b);
      v[b]++;
   }
   long long count = 1;
   vector <long long> w;
   for (map<long long, long long> :: iterator j = v.begin(); j != v.end(); j++)
       w.push_back((*j).second);
    sort(w.begin(), w.end());
    for (i = w.size() - 1; i > 0; i--)
       if (w[i] - 10<= w[i - 1])
          count ++;
       else break;
    cout << count;
}

#include <iostream>
#include <vector>
#include <string.h>
#include <functional>
#include <algorithm>
#include <math.h>
#include <cstdio>
#include <queue>
#include <string>
#include <sstream>
#include <cstdlib>
#include <map>
#include <fstream>
using namespace std;

int a,b,m,r, i, j, period;
  vector<int> vec;
int main(){
  cin>>a>>b>>m>>r;
  vec.push_back(r);
  for(i = 1; i <= 10000; ++i){
    if(i == 1)vec.push_back((a * r + b) % m);
    else vec.push_back((a * vec[i - 1] + b) % m);
  }
  period = vec.size() + 1;
  for(i = vec.size(); i >= 0; i--){
    for(j = i - 1; j >= 0; j--){
      if(vec[i] == vec[j]){
	period = min(period, i - j);
      }
    }
  }
  if(period == vec.size())period = m;
  cout<<period<<endl;
  return 0;
}

#include <iostream>
using namespace std;

int main()
{
	int mass[100] = {0};
   int a,b,m,r;
   cin >> a >> b >> m >> r;
   mass[0] = r;

   for(int i = 1; i < 100; ++i)
   	mass[i] = (a*mass[i-1] + b)%m;

   int period = 0;

   for(int i = 0; i < 100; ++i)
   	for(int j = (i+1); j < 100; ++j)
      	if(mass[i] == mass[j])
         {
         	if(mass[i] == mass[j + (j-i)] && (mass[i] == mass[j + 2*(j-i)]))
         		period = (j - i);
            break;
         }

   cout << period;

	return 0;
}

#include<bits/stdc++.h>
#define MAX 100007
using namespace std;
int main(){

int a,b,m,x[MAX],i,j,visit[MAX],c,ans,cou=0;
memset(visit,0,sizeof(visit));
cin >> a >> c>> m >> x[0];

 for(i=1; i<=m+1; i++)
    {
        x[i]=(a*x[i-1]+c)%m;
    }

for(i=1; i<=m+1; i++){
    if(visit[x[i]]==0){
        visit[x[i]]=cou;
        cou++;
    }
    else if(visit[x[i]]>0){
        ans=cou-visit[x[i]];
        break;
    }
}

cout << ans << "\n";
return 0;
}

#include<iostream>
#include<stdio.h>
using namespace std;

#define MAX 1000000
long long num[MAX+1];
long long next[MAX+1];

int getnext(int t)
{
	int i=0, j =-1;
	next[0] = -1;
	while( t+i < MAX ) {
		if(j == -1 || num[i+t] == num[j+t]){
			++i;
			++j;
			next[i] = j;
		}else j = next[j];
	}

	int ans = i-next[i];
	if(i%ans == 0 && i != ans){
		cout << i - next[i] << endl;
		return 1;
	}
	return 0;
}

int main()
{
	long long a, b, m, r0;
	while( cin >> a >> b >> m >> r0) {
		num[0] = r0;
		for(int i=1; i<MAX; ++i)
			num[i] = (a*num[i-1]+b)%m;

		for(int i=MAX-10000; i<MAX; ++i)
			if (getnext(i)) break;

	}
	return 0;
}

#include <cstdio>
#include <cstring>

int main(int argc, char* argv[]) {
	unsigned a, b, m, r;
	scanf("%d%d%d%d", &a, &b, &m, &r);
	bool buf[100000];
	memset(buf, false, sizeof(buf));
	buf[r] = true;
	for (int i = 2; ; ++i)
		if (buf[r = (r * a + b) % m]) {
			printf("%d\n", i - buf[r]);
			return 0;
		}
		else buf[r] = i;
}

#include<iostream>
#include<vector>
using namespace std;

int main()
{
long m,t;
vector<long>r;
int a,b;
cin>>a>>b>>m;
cin>>t;
r.push_back(t);
if(a==1&&b==1)
cout<<m-t-1;
else
{
x:
r.push_back((a*r[r.size()-1]+b)%m);

unsigned long j;
for( j=0;j<r.size()-1;j++)
{
if(r[j]==r[r.size()-1])
break;
}
if(j<r.size()-1)
{
cout<<r.size()-j-1;

}
else goto x;
 }
return 0;
 }

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<vector>
#include<string>
#include<sstream>
#include<set>
#include<map>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<complex>
#include<algorithm>

#define pb push_back
#define sz size()
#define clr clear()
#define EPS (1e-10)
#define INF 500000000
#define fs first
#define sc second

#define REP(i,a) for(int i=0;i<(int)(a);i++)
#define let(i,a) __typeof(a)i=(a)
#define all(a) (a).begin(),(a).end()
#define each(i,a) for(let(i,(a).begin());i!=(a).end();i++)
#define INIT(i) memset(i,0,sizeof(i))
#define EQ(a,b) (abs((a)-(b)) < EPS)
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> P;
typedef complex<double> Po;

int main(){
  int a,b,m,r;
  int memo[10010] = {},t = 0;

  cin >> a >> b >> m >> r;

  while(!memo[r]){
    memo[r] = ++t;
    r = (a*r+b)%m;
  }
  cout << ++t - memo[r] << endl;
}

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <memory.h>
using namespace std;
long long a,b,m,r0;
long long first[10005];
int main()
{
    cin>>a>>b>>m>>r0;
    memset(first,-1,sizeof first);
    first[r0]=0;
    for (long long i=1;;i++)
    {
        r0=(r0*a+b)%m;
        if (first[r0]!=-1)
        {cout<<(i-first[r0])<<endl;break;}
        else
        {first[r0]=i;}
    }
}

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
    int a,b,m,r;
    int a1[100005],c(0);
    scanf("%d %d %d %d",&a,&b,&m,&r);
    for(; !a1[r]; r=(r*a+b)%m)
        a1[r] = ++c;

    printf("%d\n",(c-a1[r]+1));
    return 0;
}

#include <iostream>
#include <bits/stdc++.h>
#define foor(i,t,n) for(int i=t;i<n;i++)
#define foorf(i,t,n) for(int i=t;i<n;i++)
#define foorb(i,t,n) for(int i=n-1;i>=t;i--)
bool flag[100009];
int arr[100009];
using namespace std;

int main()
{
    int a,b,m,r,curr,cnt=0;
    cin>>a>>b>>m>>r;
    arr[0]=r;
    for(int i=1; i<100009; i++)
    {

        arr[i]=(a*arr[i-1]+b)%m;
        //cout<<arr[i]<<endl;
        if(!flag[arr[i]]){
            flag[arr[i]]=1;
        }
        else
        {
            curr=i;
          //  cout<<"CURR : " <<i<<endl;
            break;
        }

    }
    for(int i=0; i<100009; i++)
    {
        if(arr[curr]==arr[i])
        {
          //  cout<<"I : "<<i<<endl;
            cout<<curr-i<<endl;
            return 0;
        }
    }
    return 0;
}

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

#define pb push_back
#define mp make_pair
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(),(v).end()
#define f(i,a,b) for(int i=(a);i<(b);++i)
#define fr(i,a,b) for(int i=(a);i>(b);--i)
#define fe(i,a,b) for(int i=(a);i<=(b);++i)
#define fre(i,a,b) for(int i=(a);i>=(b);--i)
string itoa(int i) { stringstream ss; ss<<i; return ss.str(); }
#define same(a,b) (fabs((a)-(b))<0.0000001)
#define even(a) ((a)%2==0)
#define odd(a) ((a)%2==1)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x))
#define MOD 1000000007
#define ull unsigned long long

int main()
{
	int a, b, m, r0;
	cin >> a >> b >> m >> r0;
	vector<int> v;
	int r = (a*r0 + b) % m;
	f(i,0,60100) {
		if(i > 30000) v.push_back(r);
		r = (a*r + b) % m;
	}
	int res = 0;
	f(i,0,v.size()) {
		int target = v[i];
		vector<int> vi;
		f(j,0,v.size()) {
			if(target == v[j]) vi.push_back(j);
		}
		bool cycle = true;
		if(vi.size() > 2) {
			f(j,min(10,(int)vi.size()/2),min((int)vi.size()-1,(int)100)) {
				if(vi[j]-vi[j-1] != vi[j+1]-vi[j] || find_first_of(v.begin()+vi[j-1],v.begin()+vi[j]+1,v.begin()+vi[j],v.begin()+vi[j+1]+1) == v.begin()+vi[j]+1) {
					cycle = false;
					break;
				}
				else {
					res = vi[j] - vi[j-1];
				}
			}
			if(cycle) break;
		}
	}
	cout << res << endl;
	return 0;
}

/* Man Mohan Mishra aka m17
   IIIT - Allahabad */
#include <cstdio>
#include <cmath>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <utility>
#include <string>
#include <vector>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <set>
#include <iterator>

#define MOD 1000000007
#define INF 1000000000000000000
#define PI acos(-1)

using namespace std;

long long GCD (long long a,long long b) {
	if (b == 0) return a;
	return(a % b == 0 ? b : GCD(b,a % b));
}

long long POW (long long base,long long exp) {
	long long val;
	val = 1;
	while (exp > 0) {
		if (exp % 2 == 1) {
			val = (val * base) % MOD;
		}
		base = (base * base) % MOD;
		exp = exp / 2;
	}
	return val;
}

int occur[100005];

int main()
{
	int a,b,m,r0,i,num;
	scanf("%d%d%d%d",&a,&b,&m,&r0);
	memset(occur,-1,sizeof(occur));
	for (i = 1; i <= 1e5; i++) {
		num = (a * r0 + b) % m;
		if (occur[num] == -1) {
			occur[num] = i;
		} else {
			printf("%d\n",i - occur[num]);
			return 0;
		}
		r0 = num;
	}
	return 0;
}

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

#define pb push_back
#define mp make_pair
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(),(v).end()
#define f(i,a,b) for(int i=(a);i<(b);++i)
#define fr(i,a,b) for(int i=(a);i>(b);--i)
#define fe(i,a,b) for(int i=(a);i<=(b);++i)
#define fre(i,a,b) for(int i=(a);i>=(b);--i)
string itoa(int i) { stringstream ss; ss<<i; return ss.str(); }
#define same(a,b) (fabs((a)-(b))<0.0000001)
#define even(a) ((a)%2==0)
#define odd(a) ((a)%2==1)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x))
#define MOD 1000000007
#define ull unsigned long long

int main()
{
	int a, b, m, r0;
	cin >> a >> b >> m >> r0;
	vector<int> v;
	int r = (a*r0 + b) % m;
	f(i,0,500000) {
		if(i > 30000) v.push_back(r);
		r = (a*r + b) % m;
	}
	vector<vector<int> > vi(m+1,vector<int>());
	f(i,0,v.size()) {
		vi[v[i]].push_back(i);
	}
	int res = 0;
	f(i,0,vi.size()) {
		if(vi[i].size() < 4) continue;
		bool cycle = true;
		int _res = 0;
		f(j,1,vi.size()-1) {
			if(vi[i][j]-vi[i][j-1] != vi[i][j+1]-vi[i][j] || find_first_of(v.begin()+vi[i][j-1],v.begin()+vi[i][j]+1,v.begin()+vi[i][j],v.begin()+vi[i][j+1]+1) == v.begin()+vi[i][j]+1) {
				cycle = false;
				break;
			}
			else {
				_res = vi[i][j] - vi[i][j-1];
			}
		}
		if(cycle) res = max(res, _res);
	}
	cout << res << endl;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll a,b,m,r0,i;
cin>>a>>b>>m>>r0;

ll x[100001];
x[0]=r0;
for(i=1;i<100001;i++)
{
 x[i]=(a*x[i-1]+b)%m;
}
map<ll,ll>mp,pos;
for(i=1;i<100001;i++)
{
 mp[x[i]]++;
 if(mp[x[i]]==2)
 {
  cout<<i-pos[x[i]]<<"\n";return 0;
 }
 pos[x[i]]=i;
}

}

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

#define pb push_back
#define mp make_pair
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(),(v).end()
#define f(i,a,b) for(int i=(a);i<(b);++i)
#define fr(i,a,b) for(int i=(a);i>(b);--i)
#define fe(i,a,b) for(int i=(a);i<=(b);++i)
#define fre(i,a,b) for(int i=(a);i>=(b);--i)
string itoa(int i) { stringstream ss; ss<<i; return ss.str(); }
#define same(a,b) (fabs((a)-(b))<0.0000001)
#define even(a) ((a)%2==0)
#define odd(a) ((a)%2==1)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x))
#define MOD 1000000007
#define ull unsigned long long

int main()
{
	int a, b, m, r0;
	cin >> a >> b >> m >> r0;
	vector<int> v;
	int r = (int)(((long long)a*r0+b)%m);
	f(i,0,700000) {
		if(i > 500000) v.push_back(r);
		r = (int)(((long long)a*r+b)%m);
	}
	vector<vector<int> > vi(m+1,vector<int>());
	f(i,0,v.size()) {
		vi[v[i]].push_back(i);
	}
	int res = 0;
	f(i,0,vi.size()) {
		if(vi[i].size() < 4) continue;
		bool cycle = true;
		int _res = 0;
		f(j,1,vi[i].size()-1) {
			if(vi[i][j]-vi[i][j-1] != vi[i][j+1]-vi[i][j]) {
				cycle = false;
				break;
			}
			int u = vi[i][j-1], w = vi[i][j];
			while(u <= vi[i][j] && w <= vi[i][j+1]) {
				if(v[u] != v[w]) { cycle = false; break; }
				u++; w++;
			}
			if(!cycle) break;
			_res = vi[i][j] - vi[i][j-1];
		}
		if(cycle) res = max(res, _res);
	}
	cout << res << endl;
	return 0;
}

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<iostream>
#include<utility>
using namespace std;
int vis[10010];
int  main()
{
	long long a,b,m,r,cur=0;cin>>a>>b>>m>>r;
	memset(vis,0,sizeof(vis));
	while(1)
	{
		++cur;
		r=((a*r)+b)%m;
//		cout<<r<<endl;
		if(vis[r])
		{
			cout<<cur-vis[r]<<endl;
			return 0;
		}
		vis[r]=cur;
	}
}

#include <stdio.h>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cmath>
#include <memory.h>

using namespace std;

int main()
{
    int a,b,m,r;
    int f[10002];
    while (cin >> a >> b >> m >> r)
    {
        memset(f,0,sizeof f);
        f[r] = 1;
        for (int i = 2; ; i++)
        {
            if (f[r=(r*a+b)%m])
            {
                cout << i - f[r] << endl;
                return 0;
            }else
            {
                f[r] = i;
            }
        }
    }
    return 0;
}

#include <iostream>
#include <fstream>
#include <conio.h>
#include <string>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <set>

#define PB push_back
using namespace std;
int a,b,m,r;
vector<int> t,k;
bool cek(vector<int> t,int p){
	vector<int> :: iterator it;
	for(it = t.begin();it!=t.end();it++){
		if(p == *it) return true;
	}
	return false;
}
int main()
{
//    ifstream cin ;
//    cin.open("test.txt");
//while(!cin.eof())
//{
	cin >> a >> b >> m >> r;
	int push;
	bool flag = true;
	int c = 0;
	while(flag){
		push = ((a*r) + b) % m;
		cout << "push : " << push << endl;
		if(cek(t,push)){
			if(cek(k,push)){
				c++;
			}
			else{
				k.PB(push);
			}
		}
		else{
			k.clear();
			t.PB(push);
			c = 0;
		}
		r = push;
		if(c == (int) k.size() && c != 0){
			flag = false;
		}
	}
	cout << (int) k.size() << endl;
//}
//    cin.close();
//    getch();
    return 0;
}

#include <iostream>

using namespace std;

int arr[10000];

int main() {
	int a, b, m ,r;

    cin >> a >> b >> m >> r;
	int i = 0;
	while (1){
		int buffer = (a * r + b ) % m;
		if (arr[buffer]) {
			cout << i - arr[buffer];
			break;
		}
		arr[buffer] = i++;
		r = buffer;
	}

    return 0;
}

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <ctime>
#include <iomanip>
#include <iterator>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <stdio.h>
#include <cstring>

#define ii <int , int>

#define mp make_pair
#define all(v) v.begin(),v.end()
#define loop(i, n) for (int i = 0; i < n; i++)
#define pb push_back
#define sz(v) (int)v.size()
#define X first
#define Y second

#define Pi(x) printf("%d ", (x))
#define Pii(x, y) printf("%d %d ", (x), (y))
#define Piii(x, y, z) printf("%d %d %d", (x), (y), (z))
#define Pl(x) printf("%I64d ", (x))
#define Pll(x, y) printf("%I64d I64d ", (x), (y))
#define Plll(x, y, z) printf("%I64d I64d I64d ", (x), (y), (z))
#define Ps(x) printf("%s", (x))
#define Pe() printf("\n")
#define Pe1(i) for (int j = 0; j < i; j++) printf(" ")

#define Si(x) scanf("%d",&x)
#define Sii(x, y) scanf("%d %d", (&x), (&y))
#define Siii(x, y, z) scanf("%d %d %d", (&x), (&y), (&z))
#define Sl(x) scanf("%I64d", (&x))
#define Sll(x, y) scanf("%I64d %I64d", (&x), (&y))
#define Slll(x, y, z) scanf("%I64d %I64d %I64d", (&x), (&y), (&z))
#define Ss(x) scanf("%s", (&x))

using namespace std;

typedef long long ll;
typedef vector<int > vi;
typedef vector<vi> vvi;
typedef pair ii pii;
typedef vector <pii> vii;
typedef map ii mii;
typedef set <int > si;
typedef multiset <int > msi;
typedef multimap <int , int> mmi;
typedef vector <ll> vl;
typedef pair<ll, ll> pll;
typedef vector <pll> vll;

const ll nInf = -1000000000;
const ll pInf = 1000000000;
const ll mod     = 1000000007;
const int MAXN = 1000;

int a, b, m, r[MAXN], used[MAXN];
void getdata();
void preproc();
void solve();
int main()
{
      //  freopen( "input.txt", "r" , stdin);
      //  freopen( "output.txt", "w" , stdout);
        int t = 1;
      //  scanf("%d", &t);
        for (int i = 0;i < t; i++)
        {
               getdata();
               preproc();
               solve();
        }
        return 0;
}

void getdata()
{
	scanf("%d %d %d %d", &a, &b, &m, &r[0]);
}

void preproc()
{

}

void solve()
{
	fill(used, used + MAXN, -1);
	for (int i = 1; i < 100000000; i++)
	{
		r[i] = (a * r[i - 1] + b) % m;
		if (used[r[i]] != -1)
		{
			printf("%d\n", i - used[r[i]]);
			return;
		}
		used[r[i]] = i;
	}
}

#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
vector <int> mrSequence;

int ladyCheckCurrentSequencePosition(int mrSequenceIterator) {
    int mrCheckIterator;
    for (mrCheckIterator = 5; mrCheckIterator < mrSequenceIterator; mrCheckIterator++)
        if (mrSequence[mrSequenceIterator] == mrSequence[mrCheckIterator])
            return (mrSequenceIterator - mrCheckIterator);
    return -1;
};

int main(int argc, char** argv) {
    int mrA; int mrB; int mrsM; int mrR0;
    int mrResult;
    int mrSequenceIterator;
    cin >> mrA; cin >> mrB; cin >> mrsM; cin >> mrR0;
    mrSequence.push_back(mrR0);
    for (mrSequenceIterator = 1; mrSequenceIterator < 2000; mrSequenceIterator++) {
        mrSequence.push_back((mrA * mrSequence[mrSequenceIterator-1] + mrB) % mrsM);
        mrResult = ladyCheckCurrentSequencePosition(mrSequenceIterator);
        if (mrResult > 0)
            break;
    };
    cout << mrResult;
    return 0;
};

#include <iostream>
#include <vector>
using namespace std;

int euc (int  a, int b)
{
    if (a==0)
        return b;
    return euc(b%a,a);
}

int gcd (int a, int b)
{
    if (a<=b) return euc(a,b);
    else return euc(b,a);
}

int phi (int n)
{
    int result = n;
    for (int i=2; i*i<=n; ++i)
        if (n%i==0)
        {
            result-=result/i;
            while (n%i==0)
                n/=i;
        }

    if (n>1)
        result-=result/n;
    return result;
}

int main()
{
    int a,b,m,r;
    cin>>a>>b>>m>>r;
    int ans=-1;

    do
    {
        int c=a*r-r+b;
        int g=gcd(c,m);
        int m1=m/g;

        if (gcd(a,m1)==1)
            ans=phi(m1);

        r=(a*r+b)%m;
    }
    while (ans==-1);

    cout<<ans<<endl;
}

//SORU xx
//PROGRAM C
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<limits.h>
#include<time.h>
#include<ctype.h>
//#include<math.h>
#define scn(x) fscanf(in,"%d",&x);
#define prn(x) fprintf(out,"%d\n",x);
#define prn2(x) fprintf(out,"%d",x);
#define line() fprintf(out,"\n");
#define wait system("PAUSE");
#define scn2(x,y) scn(x);scn(y);
FILE *in,*out;
void dosya(){
		/*in=fopen("girdi.in","r");*/in=stdin;
		/*out=fopen("cikti.out","w");*/out=stdout;
}
int a,b,m,r,d[10000];
void oku(){
	fscanf(in,"%d%d%d%d",&a,&b,&m,&r);
	int i;
	d[0]=r;
	for(i=1; i<10000; i++)
		d[i]=(a*d[i-1]+b)%m;
}
int coz(){
	int i,tut,son=0,j,c=0;
	for(i=0; i<10000; i++){
		tut=d[i];
		for(j=i+1; j<10000; j++){
			if(d[j]==tut){
				c++;
				break;
			}
			son++;
		}
		if(son && c)
			break;
		if(!c) son=0;
	}
	return son;
}
int main(){
	dosya();
	oku();
	int t=coz();
	fprintf(out,"%d",t+1);
	return 0;
}

#include<iostream>

using namespace std;

int main(){

    int Z,I,M,L;
    int x1,x2,n,m,caso;
        cin>>Z>>I>>M>>L;

        x1=L;
        x2=L;

        m=0;

        do{
            x1=(x1*Z+I)%M;
            x2=(x2*Z+I)%M;
            x2=(x2*Z+I)%M;
            m++;
        }while(x1!=x2);
    return 0;
}

#include <iostream>

using namespace std;
int a,b,m,r0,r,i=0,j,nr,viz[10000],v[10000];
int main()
{ int o=1;
cin>>a>>b>>m>>r0;
r=r0;
while(o++)
{
    r=(a*r+b)%m;
    v[i]=r;
    viz[r]++;
    if(viz[r]==2)
    {
        for (j=i-1;j>=0;j--)
        {
            nr++;
            if(viz[v[j]]==2)
            {
                break;
            }
        }
        break;
    }

    i++;
}
cout<<nr;
    return 0;
}

#include <iostream>
using namespace std;
int niz[1000];
int main()
{
    int a,b,m,r0;
    cin >> a >> b >> m >> r0;
    niz[0]=r0;
    for(int i=1;i<1000;i++)
    {
    niz[i]=(a*niz[i-1]+b)%m;
    }
    int br=niz[999];
    for(int i=998;i>0;i--)
    if (niz[i]==br) {cout << 999-i << endl;break;}
    //system("pause");
    return 0;
}

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include <vector>
#include <map>
#include <set>
#include <utility>
#include <deque>
#include <cmath>
#include <functional>
#include<iomanip>
using namespace std;
#define ll long long int

int main()
{
ll a,b,m,r0,r[1000000],i,j,count=0,f=0;
cin>>a>>b>>m>>r0;

r[0]=(a*r0+b)%m;
/*for(i=0;i<m+1;i++)
{
r[i+1]=(a*r[i]+b)%m;
}*/
for(i=0;i<m+1;i++)
{cout<<" "<<r[i];}
for(i=0;i<m+1;i++)
{ for(j=i+1;j<m+1;j++)
    {
        if(r[i]==r[j])
           {
            count=j-i;
            f=1;}
if(f==1)
break;
}

if(f==1)
break;
}
cout<<"ANS"<<count<<endl;
}

#include <cstdio>

bool hash[10001];

int a, b, m;
int r[10001];

int main()
{
    //freopen("input.txt", "r", stdin);
    scanf("%d %d %d %d", &a, &b, &m, &r[0]);
    hash[r[0]] = true;
    int el = -1;
    int N = 0;

    for(int i = 1; i < 11000; i++)
    {
        r[i] = (a * r[i-1] + b) % m;
        //printf("%d ", r[i]);
        if (hash[r[i]] == true)
        {
            el = r[i];
            N = i;
            break;
        }
        else
        {
            hash[r[i]] = true;
        }
    }

    for(int i = 0; i < N; i++)
    {
        if (r[i] == el)
        {
            printf("%d", N - i);
            return 0;
        }
    }

    printf("0");

    return 0;
}

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

#define pb push_back
#define mp make_pair
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(),(v).end()
#define f(i,a,b) for(int i=(a);i<(b);++i)
#define fr(i,a,b) for(int i=(a);i>(b);--i)
#define fe(i,a,b) for(int i=(a);i<=(b);++i)
#define fre(i,a,b) for(int i=(a);i>=(b);--i)
string itoa(int i) { stringstream ss; ss<<i; return ss.str(); }
#define same(a,b) (fabs((a)-(b))<0.0000001)
#define even(a) ((a)%2==0)
#define odd(a) ((a)%2==1)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x))
#define MOD 1000000007
#define ull unsigned long long

int main()
{
	int a, b, m, r0;
	cin >> a >> b >> m >> r0;
	vector<int> v;
	int r = (a*r0 + b) % m;
	f(i,0,30100) {
		v.push_back(r);
		r = (a*r + b) % m;
	}
	int res = 0;
	f(i,0,v.size()) {
		int target = v[i];
		//cout << "Start " << target << endl;
		vector<int> vi;
		f(j,0,v.size()) {
			if(target == v[j]) vi.push_back(j);
		}
		bool cycle = true;
		if(vi.size() > 2) {
			//f(j,0,100) {
			//	cout << vi[j] << " ";
			//}
			//cout << endl;
			f(j,1,vi.size()-1) {
				if(vi[j]-vi[j-1] != vi[j+1]-vi[j] || find_first_of(v.begin()+vi[j-1],v.begin()+vi[j]+1,v.begin()+vi[j],v.begin()+vi[j+1]+1) == v.begin()+vi[j]+1) {
					cycle = false;
					break;
				}
				else {
					res = vi[j] - vi[j-1];
				}
			}
			if(cycle) break;
		}
	}
	cout << res << endl;
	return 0;
}

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <string>
using namespace std;

int main(){
    int a,i,b,m,r[1000000],N;
    cin >> a >> b >> m >> r[0];
    int n[m];
    N = 0;
    for (i=0;i<=m;i++){
        n[i]=0;
    }

    for (i=1;i<=999999;i++){
        r[i]=(a*r[i-1]+b) % m;
        n[r[i]]+=1;
    }

    for (i=0;i<=m;i++){
        if (n[i] >= 300){
           N++;
        }
    }

    cout << N;
}

#include<iostream>
#include<cstdlib>
#include<cmath>
#include<set>
using namespace std;
set<int> c, d;

int a,b,m,r[50000];

inline int f(int k){
       return (a * r[k-1] + b) % m;
}
int main(){

    cin>>a>>b>>m>>r[0];
    for(int i = 1; i < 50000; i++){
            r[i] = f(i);
            if(c.find(r[i]) == c.end()){
                            c.insert(r[i]);
            }else {
                  if(d.find(r[i]) == d.end())
                    d.insert(r[i]);
                  else break;
            }
    }
      cout<<d.size();
 //     system("pause");
      return 0;
}

#include <iostream>
#include <cstring>

using namespace std;

long long H[50001];

long long getNext(long long a, long long b, long long m, long long r0){
    return (a*r0 + b)%m;
}

int main(){
    long long a,b,m,r;
    cin >> a >> b >> m >> r;

    memset(H, 0, sizeof(H));

    long long i = 0;

    while(1){
        i++;
        r = getNext(a,b,m,r);
        if (H[r]) break;
        H[r] = i;
    }

    cout << (i - H[r]) << endl;

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
int a,b,m,r,p;
int s[10005];
int main()
{
    cin>>a>>b>>m>>r;
    while(1)
    {
        p++;
        r=(a*r+b)%m;
        if(s[r]==0)
        s[r]=p;
        else
        {
            cout<<p-s[r];
            return 0;
        }
    }
    return 0;
}

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

template<typename T>
using ordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;

#define ll long long
#define ull unsigned long long
#define __   ios_base::sync_with_stdio(0);cin.tie();cout.tie();

string s,s1,s2,s3,s4,s5;
ll n,m,x,y,z;
ll arr[500010];
ll brr[500010];
vector<ll>v,v1;
set<ll>st;

void memset_ll(ll a[], ll v, ll n)
{
    for(ll i=0; i<n; i++)
        a[i]=v;
}

int compare(const void * a, const void * b)
{
    return ( *(ll*)a - *(ll*)b );
}
void q_sort(ll a[], ll n)
{
    qsort(a, n, sizeof(ll), compare);
}

ll is_prime(ll n)
{
    ll i,j,k=1;
    for(i=2; i<=n/2; i++)
    {
        if(n%i==0)
        {
            k=0;
            break;
        }
    }
    return k;
}

ll bsearch(ll arr[], ll l, ll r, ll x)
{
    if (r >= l)
    {
        ll mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return bsearch(arr, l, mid - 1, x);
        return bsearch(arr, mid + 1, r, x);
    }
    return -1;
}

static int compare1 (const void * a, const void * b)
{
    if (*(double*)a > *(double*)b)
        return 1;
    else if (*(double*)a < *(double*)b)
        return -1;
    else
        return 0;
}

void q_sort_d(double a[], ll n)
{
    qsort(a, n, sizeof(double), compare1);
}

string trans_upper(string ss)
{
    transform(ss.begin(),ss.end(),ss.begin(), ::toupper);
    return ss;
}

ll power(ll a, ll b)
{
    ll pow = 1;
    while ( b )
    {
        if ( b & 1 )
        {
            pow = pow * a;
            --b;
        }
        a = a*a;
        b = b/2;
    }
    return pow;
}

int main()
{
    __
    ll t,h,i,j,k,l,p,q,r;
    ll d=0,e=0,f=0,g=0;
    ll dd=0,uu=0,rr=0,lll=0;
    ll ans=0,sum=0,temp=0;
    ll x1,y1,x2,y2;

    double p1,p2,p3,p4,p5;
    double pp=0.0,ppp=1.0;
    double pi =3.141592654;

    cin>>x>>y>>z>>r;
    ll a[10000];
    a[0]=(x*r+y)%z;
    for(i=1;i<10000;i++)
    {
        r=a[i-1];
        a[i]=(x*r+y)%z;
    }
    for(k=1;k<10000;k++)
    {
        for(j=9999;j>=0;j--)
        {
            if(a[j]==a[j-k]&&a[j-1]==a[j-1-k])
            {
                cout<<k;
                return 0;
            }
            else
                break;
        }
    }

    return 0;
}

///*Bismillahir Rahmanir Rahim***///
/***Stay_Home_Stay_Safe***/
///**Author Thasin Sheikh**///
/*while(a)
    {
        if(a%2==0)
            dvi.push_back(0);
        else
            dvi.push_back(1);
        a/=2;
    }
    reverse(dvi.begin(),dvi.end());*/
#include<bits/stdc++.h>
using namespace std;
#define MAX 35000
#define makefast__  ios_base::sync_with_stdio(false);
using ll=long long int  ;
using dl =double;
const int N = 2e5 + 10;
ll aarray[200000+10];
ll magic[101][101];
vector<ll>primes;
bool fk[1000001];
ll a,b,m,r0;
ll solve(ll i)
{
    ll re;
    re=((r0*a)+b)%m;
    primes.push_back(re);
    r0=re;
    return re;

}
int main()
{
    makefast__
    string str;
    ll c,d,e,f,x,y,t,A,B=0,L,j,i,l,r,n,C=0,ans=0,sum=0,sum1=0;
    vector<ll>v,v1;
    queue<ll>qu;
    set<ll>sl;
    cin>>a>>b>>m>>r0;
    ll cnt=0;
    for(i=1;i<=a+10;i++)
    {
        x=solve(i);
        if(sl.find(x)!=sl.end())
        {
            A=x;
            break;
        }
        else{
        sl.insert(x);
        cnt++;}
    }
    for(i=0;i<primes.size();i++)
    {
        if(primes[i]!=A)
            B++;
        else break;
    }
    cout<<cnt-B<<endl;

    return 0;
}

#include <cstdio>

bool hash[10001];

int a, b, m;
int r[10001];

int main()
{
    //freopen("input.txt", "r", stdin);
    scanf("%d %d %d %d", &a, &b, &m, &r[0]);
    int el = -1;
    int N = 0;

    for(int i = 1; i < 10002; i++)
    {
        r[i] = (a * r[i-1] + b) % m;
        //printf("%d ", r[i]);
        if (hash[r[i]] == true)
        {
            el = r[i];
            N = i;
            break;
        }
        else
        {
            hash[r[i]] = true;
        }
    }

    for(int i = 1; i < N; i++)
    {
        if (r[i] == el)
        {
            printf("%d", N - i);
            return 0;
        }
    }

    printf("0");

    return 0;
}

#include<iostream>
#include<stdio.h>
using namespace std;

#define MAX 150000
long long num[MAX+1];
long long next[MAX+1];

int getnext(int t)
{
    int i=0, j =-1;
    next[0] = -1;
    while( t+i < MAX ) {
        if(j == -1 || num[i+t] == num[j+t]){
            ++i;
            ++j;
            next[i] = j;
        }else j = next[j];
    }

    int ans = i-next[i];
    if(i%ans == 0 && i != ans){
        cout << i - next[i] << endl;
        return 1;
    }
    return 0;
}

int main()
{
    long long a, b, m, r0;
    while( cin >> a >> b >> m >> r0) {
        num[0] = r0;
        for(int i=1; i<MAX; ++i)
            num[i] = (((a%m)*(num[i-1]%m))%m+b%m)%m;
        for(int i=MAX-5000; i<MAX; ++i)
            if(getnext(i)) break;

    }
    return 0;
}

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    bool visit[10000];
    int store[10000];
    int a,b,m,r0,mark;
    while(cin>>a>>b>>m>>r0)
    {
        memset(visit,false,sizeof(visit));
        store[0]=r0;
        for(int i=1;;i++)
          {
            store[i]=(a*store[i-1]+b)%m;
            if(visit[store[i]]==false)
                visit[store[i]]=true;
            else
            {
                mark=i;
                break;
            }
        }
        for(int j=1;j<mark;j++)
        {
            if(store[j]==store[mark])
            {
                cout<<mark-j<<endl;
                break;
            }
        }
    }
 }

#include<bits/stdc++.h>
using namespace std;
#define int long long int
#define double long double
#define pb push_back
#define endl '\n'
#define all(x) (x).begin(),(x).end()
#define F first
#define S second
#define sz(a) (int)((a).size())
#define fuck() cout<<"--------"<<endl
#define see(x) cout<<#x<<" = "<<x<<endl
#define see2(x,y) cout<<#x<<" = "<<x<<"::"<<#y<<" = "<<y<<endl
const int mod=1000000007;
typedef pair<int,int> pii;
const int N=1e5+5;
int dp[N];
int32_t main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
    memset(dp,-1,sizeof(dp));
    int a,b,m,r;
    cin>>a>>b>>m>>r;
    dp[r]=0;
    int tmp=r;
    for(int i=1;;i++){
        tmp=(a*tmp+b)%m;
        if(dp[tmp]!=-1){
            cout<<i-dp[tmp];
            return 0;
        }
        dp[i]=tmp;
    }
}

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

#define PEACE std::ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define DECIMAL(n)  std::cout << std::fixed;std::cout << std::setprecision(n);
#define hell 1000000007
#define PI 3.14159265358979323844
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ALL(v) v.begin(), v.end()
#define SORT(v) sort(ALL(v))
#define REVERSE(v) reverse(ALL(v))
#define endl "\n"
#define maxc(v) max_element(all(v))
#define minc(v) min_element(all(v))
#define GCD(m,n) __gcd(m,n)
#define LCM(m,n) m*(n/GCD(m,n))
#define inputarr(a,n) for(int i=0;i<n;++i) cin>>a[i]
#define initarr(a,n,x) for (int i=0;i<n;++i) a[i]=x
#define rep(i, n)    for(int i = 1; i <= (n); ++i)
#define repA(i, a, n)  for(int i = a; i <= (n); ++i)
#define repD(i, a, n)  for(int i = a; i >= (n); --i)
#define trav(a, x) for(auto& a : x)
#define sz(a) (int)a.size()
#define sl(a) (int)a.length()
#define invect(data,n,commands) for(int i = 0;i<n;i++){int tmp;cin>>tmp;data.pb(tmp);commands}
#define inset(data,n,commands) for(int i = 0;i<n;i++){int tmp;cin>>tmp;data.insert(tmp);commands}
#define display(x) trav(a,x) cout<<a<<" ";cout<<endl

#define ll long long int
typedef long double ld;
#define pii std::pair<int, int>
#define pll std::pair<ll, ll>
#define vi vector<int>
#define vvi vector<vi >
#define vii vector<pii >
#define MOD 998244353
#define N 10000005

ll rvrs(ll x)
{
  ll y=0;
  while(x>0)
  {
    y *= 10;
    y += x%10;
    x = x/10;
  }
  return y;
}

ll n,m,k;

void solve()
{
  ll r,a,b;
  cin >> a >> b >> m >> r;
  vector <ll> v[100005];

  for(ll i=0;i<100000;i++)
  {
    r = (a*r+b)%m;
    v[r].pb(i);
  }
  ll ans = 1e9;
  for(ll i=0;i<100000;i++)
  {
    if(v[i].size()>1)
    {
      ans = min(ans,(v[i][1]-v[i][0]));
    }
  }
  cout << ans << endl;
}

int main(){

  PEACE

  ll t=1;
  while(t--)
  {
   solve();
  }

  return 0;
}

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

template<typename T>
using ordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;

#define ll long long
#define ull unsigned long long
#define __   ios_base::sync_with_stdio(0);cin.tie();cout.tie();

string s,s1,s2,s3,s4,s5;
ll n,m,x,y,z;
ll arr[500010];
ll brr[500010];
vector<ll>v,v1;
set<ll>st;

void memset_ll(ll a[], ll v, ll n)
{
    for(ll i=0; i<n; i++)
        a[i]=v;
}

int compare(const void * a, const void * b)
{
    return ( *(ll*)a - *(ll*)b );
}
void q_sort(ll a[], ll n)
{
    qsort(a, n, sizeof(ll), compare);
}

ll is_prime(ll n)
{
    ll i,j,k=1;
    for(i=2; i<=n/2; i++)
    {
        if(n%i==0)
        {
            k=0;
            break;
        }
    }
    return k;
}

ll bsearch(ll arr[], ll l, ll r, ll x)
{
    if (r >= l)
    {
        ll mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return bsearch(arr, l, mid - 1, x);
        return bsearch(arr, mid + 1, r, x);
    }
    return -1;
}

static int compare1 (const void * a, const void * b)
{
    if (*(double*)a > *(double*)b)
        return 1;
    else if (*(double*)a < *(double*)b)
        return -1;
    else
        return 0;
}

void q_sort_d(double a[], ll n)
{
    qsort(a, n, sizeof(double), compare1);
}

string trans_upper(string ss)
{
    transform(ss.begin(),ss.end(),ss.begin(), ::toupper);
    return ss;
}

ll power(ll a, ll b)
{
    ll pow = 1;
    while ( b )
    {
        if ( b & 1 )
        {
            pow = pow * a;
            --b;
        }
        a = a*a;
        b = b/2;
    }
    return pow;
}

int main()
{
    __
    ll t,h,i,j,k,l,p,q,r;
    ll d=0,e=0,f=0,g=0;
    ll dd=0,uu=0,rr=0,lll=0;
    ll ans=0,sum=0,temp=0;
    ll x1,y1,x2,y2;

    double p1,p2,p3,p4,p5;
    double pp=0.0,ppp=1.0;
    double pi =3.141592654;

    cin>>x>>y>>z>>r;
    ll a[100000];

    a[0]=(x*r+y)%z;
    for(i=1; i<100000; i++)
    {
        r=a[i-1];
        a[i]=(x*r+y)%z;
    }
    for(k=1; k<=100000; k++)
    {
        j=99999;
        if(a[j]==a[j-k]&&a[j-1]==a[j-1-k])
        {
            cout<<k;
            return 0;
        }
    }
    if(x==0||y==0)
    {
        cout<<1;
        return 0;
    }
    if(r==0)
    {
        cout<<z;
        return 0;
    }

return 0;
}

#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#define ll long long
using namespace std;
ll a, b, m, r0;
ll z[10005];
int main () {
    cin>>a>>b>>m>>r0;
    memset(z, -1, sizeof(z));
    z[r0]=0;
   for(int i=1;;i++) {
        r0 = ((ll)(a*r0 + b))%(ll)m;
        if (z[r0]!=-1) {
            cout<<i-z[r0];
            return 0;
        } else z[r0]=i;
    }
}

#include<iostream>
#include<stdio.h>
using namespace std;
int r[500000];
int main()
{
	int a,b,m,t,pos1,pos2;
	bool flag=0;
	while(cin>>a>>b>>m>>t)
	{
		int cnt=0;
		t=(a*t+b)%m;

		for(int i=1;i<=1000;i++)
		{
			r[i]=t;
			t=(a*t+b)%m;
		}

		for(int i=1;i<=1000;i++)
		{
			flag=0;
			for(int j=1;j<i;j++)
			if(r[i]==r[j])
			{
				pos1=i;
				pos2=j;
				flag=1;
				break;
			}

			bool p=0;

			if(flag)
			{
				p=1;
				int f=pos1;
				for(int d=pos2;d<pos1;d++)
				{
					if(r[d]==r[f++])
					{
						cnt++;
					}
					else
					{
						p=0;
					    break;
					}
				}
			}

			if(p)
			{
			cout<<cnt<<endl;
			break;
			}
		}
	}
	return 0;
}

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

#define pb push_back
#define mp make_pair
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(),(v).end()
#define f(i,a,b) for(int i=(a);i<(b);++i)
#define fr(i,a,b) for(int i=(a);i>(b);--i)
#define fe(i,a,b) for(int i=(a);i<=(b);++i)
#define fre(i,a,b) for(int i=(a);i>=(b);--i)
string itoa(int i) { stringstream ss; ss<<i; return ss.str(); }
#define same(a,b) (fabs((a)-(b))<0.0000001)
#define even(a) ((a)%2==0)
#define odd(a) ((a)%2==1)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x))
#define MOD 1000000007
#define ull unsigned long long

int main()
{
	int a, b, m, r0;
	cin >> a >> b >> m >> r0;
	vector<int> v;
	int r = (a*r0 + b) % m;
	f(i,0,30000) {
		v.push_back(r);
		r = (a*r + b) % m;
	}
	int res = 0;
	f(i,0,v.size()) {
		int target = v[i];
		vector<int> vi;
		f(j,0,v.size()) {
			if(target == v[j]) vi.push_back(j);
		}
		bool cycle = true;
		if(vi.size() > 2) {
			f(j,min(10,(int)vi.size()/2),min((int)vi.size()-1,(int)100)) {
				if(vi[j]-vi[j-1] != vi[j+1]-vi[j] || find_first_of(v.begin()+vi[j-1],v.begin()+vi[j]+1,v.begin()+vi[j],v.begin()+vi[j+1]+1) == v.begin()+vi[j]+1) {
					cycle = false;
					break;
				}
				else {
					res = vi[j] - vi[j-1];
				}
			}
			if(cycle) break;
		}
	}
	cout << res << endl;
	return 0;
}

#include<iostream>
using namespace std;
int main()
{
	int a,b,m,r,l=0,t,p[100000];
	bool flag=false;
	cin>>a>>b>>m>>r;
	p[l++]=t=r=(a*r+b)%m;
	for(int i=0;i<100000;i++)
	{
		p[l++]=r=(a*r+b)%m;
		for(int j=0;j<l-1;j++)
			if(p[j]==p[l-1])
			{
				if(j==0){cout<<l-1<<endl;flag=true;break;}
				else {cout<<j+1<<endl;flag=true;break;}
			}
		if(flag)break;
	}
}

#include <iostream>

using namespace std;
int a,b,m,r0,r,i=0,j,nr,viz[10000],v[10000];
int main()
{ int o=1;
cin>>a>>b>>m>>r0;
r=r0;
while(o++)
{
    r=(a*r+b)%m;
    v[i]=r;
    viz[r]++;
    if(viz[r]==2)
    {
        for (j=i-1;j>=0;j--)
        {
            nr++;
            if(viz[v[j]]==2)
            {
                break;
            }
        }
        break;
    }

    i++;
}
cout<<nr;
    return 0;
}

#include<stdio.h>
//#include<conio.h>

unsigned short mas[100000000];

int main()
{
	int a, b, m, n, j;
	scanf("%d %d %d %us", &a, &b, &m, &mas[0]);
	int i=1;
	while(1)
	{
		mas[i]=(a*mas[i-1]+b)%m;
		for(j=i-1; j>=1; j--)
			if(mas[i]==mas[j])
				goto metka;
		i++;
	}
metka:
	printf("%d", i-j);
	//getch();
	return 0;
}

#include <iostream>
#include <map>

using namespace std;

map <int, int> k;

int main()
{
  int a, b, m, r; cin>>a>>b>>m>>r;
  k[r]=1;
  for (int i=2; ; i++)
    {
                        r = (a*r+b) % m;
                        cout<<i<<"   "<<r<<" "<<k[r]<<endl;
                        if (k[r]) {cout<<i-k[r]; return 0;}
                          else k[r]=i;
    }
    return 0;
}

#include <stdio.h>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cmath>
#include <memory.h>

using namespace std;

int main()
{
    int a,b,m,r;
    int f[10002];
    while (cin >> a >> b >> m >> r)
    {
        memset(f,0,sizeof f);
        f[r] = 1;
        for (int i = 2; ; i++)
        {
            if (f[r=(r*a+b)%m])
            {
                cout << i - f[r] << endl;
                return 0;
            }else
            {
                f[r] = i;
            }
        }
    }
    return 0;
}

#include <iostream>
#include <cstring>

using namespace std;

long long H[60001];

long long getNext(long long a, long long b, long long m, long long r0){
    return (a*r0 + b)%m;
}

int main(){
    long long a,b,m,r;
    cin >> a >> b >> m >> r;

    memset(H, 0, sizeof(H));

    long long i = 1;

    H[r] = i;

    while(1){
        i++;
        r = getNext(a,b,m,r);
        if (H[r]) break;
        H[r] = i;
    }

    cout << (i - H[r]) << endl;

    return 0;
}

#include <iostream>
#include <fstream>
#include <conio.h>
#include <string>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <set>

#define PB push_back
using namespace std;
int a,b,m,r[210000],temp[210000] = {0};
vector<int> t,k;
bool cek(vector<int> t,int p){
	vector<int> :: iterator it;
	for(it = t.begin();it!=t.end();it++){
		if(p == *it) return true;
	}
	return false;
}
bool stop(vector<int> t,int p){
	vector<int> :: iterator it = t.begin();
	if(p == *it) return true;
	else return false;
}
int main()
{
//    ifstream cin ;
//    cin.open("test.txt");
//while(!cin.eof())
//{
	cin >> a >> b >> m >> r[0];
	int push;
	bool flag = true;
	int c = 0;
//	vector<int> :: iterator ic;
//	while(flag){
//		push = ((a*r) + b) % m;
//		if(!k.empty()){
//			if(stop(k,push)){
//				break;
//			}
//		}
//		if(cek(t,push)){
//			k.PB(push);
//		}
//		else{
//			t.PB(push);
//		}
//		r = push;
//	}
	for(int i=1;i<=2*m;i++){
		r[i] = ((a*r[i-1]) + b) % m;
		temp[r[i]]++;
	}
	for(int i=0;i<=2*m;i++){
		if(temp[i] > 1) c++;
	}
	cout << c;
	cout << "finish" << endl;
//}
//    cin.close();
//    getch();
    return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>

std::vector<int> prefix_function(std::vector<int>& vec, bool& hit, int& pos) {
    size_t size = vec.size();
    std::vector<int> pi(size);

    for (size_t i = 1; i < size; ++i) {
        size_t j = pi[i - 1];

        while (j > 0 && vec[j] != vec[i]) {
            j = pi[j - 1];
        }

        if (vec[j] == vec[i]) {
            ++j;
        }

        pi[i] = j;

        if (pi[i] > 0) {
            hit = true;
            pos = i;
            break;
        }
    }
    return (pi);
}

int next_rand(int prev, int a, int b, int m) {
    int rand = (a * prev + b) % m;

    return (rand);
}

std::vector<int> max_pf(std::vector<int>& rand) {
    std::vector<int> maxpf;

    int i = 0;

    for (std::vector<int>::iterator it = rand.begin(); it != rand.end();) {
        bool hit = false;
        int pos = 0;

        std::vector<int> pf = prefix_function(rand, hit, pos);
        if (hit == true) {
            maxpf.push_back(i+pos);
            return (maxpf);
        }

        rand.erase(rand.begin());
        it = rand.begin();
        i++;
    }

    return (maxpf);
}

int main() {
    int a, b, m, seed, pos = 0;
    std::vector<int> rand;
    rand.reserve(100000);

    std::cin >> a;
    std::cin >> b;
    std::cin >> m;
    std::cin >> seed;

    rand.push_back(seed);
    size_t i;
    for (i = 1; i < 1000000; ++i) {
        rand.push_back(next_rand(rand[i - 1], a, b, m));
    }

    rand.erase(rand.begin());

    while (true) {
        std::vector<int> maxpf = max_pf(rand);
        if (!maxpf.empty()) {
            std::cout << *(std::min_element(maxpf.begin(), maxpf.end())) + pos;
            break;
        } else {
            pos = i - 1;
            size_t j;
            for (j = i - 1; j < i + 10000; ++j) {
                rand.push_back(next_rand(rand[j - 1], a, b, m));
            }
            i = j + 1;
        }
    }

    return (0);
}

#include<iostream>
#include<stdio.h>
using namespace std;

#define MAX 3000000
long long num[MAX+1];
long long next[MAX+1];

int getnext(int t)
{
	int i=0, j =-1;
	next[0] = -1;
	while( t+i < MAX ) {
		if(j == -1 || num[i+t] == num[j+t]){
			++i;
			++j;
			next[i] = j;
		}else j = next[j];
	}

	int ans = i-next[i];
	if(i%ans == 0 && i != ans){
		cout << i - next[i] << endl;
		return 1;
	}
	return 0;
}

int main()
{
	long long a, b, m, r0;
	while( cin >> a >> b >> m >> r0) {
		num[0] = r0;
		for(int i=1; i<MAX; ++i)
			num[i] = (((a%m)*(num[i-1]%m))%m+b%m)%m;
		getnext(MAX-100000);

	}
	return 0;
}

// Period.cpp : Defines the entry point for the console application.
//

//#include "stdafx.h"

#include <iostream>
#include <vector>
#include <set>

int r;
void SetSeed(int r0)
{
    r = r0;
}

int GetRandom(int a, int b, int m)
{
    r = (a * r + b) % m;
    return r;
}

void PrintSec(std::vector<int>& s)
{
    for (size_t i=0; i<s.size(); ++i)
    {
        std::cout << s[i];
        if (i != s.size()-1 )
        {
            std::cout << " ";
        }
    }
}

//int _tmain(int argc, _TCHAR* argv[])
int main()
{
    int a, b, m, r0;
    std::cin >> a >> b >> m >> r0;

    std::vector<int> sequence;
    std::set<int> seqSet;
    SetSeed(r0);
    const int maxLen = 10;
    size_t period = 0;
    for (int i=0; i<maxLen; i++)
    {
        int x = GetRandom(a, b, m);
        if (seqSet.count(x))
        {
            for(size_t j=0; j<sequence.size(); ++j)
            {
                if(sequence[j] == x)
                {
                    period = sequence.size() - j;
                    break;
                }
            }
            break;
        }
        sequence.push_back(x);
        seqSet.insert(x);
    }

    std::cout << period;

    return 0;
}

#include<bits/stdc++.h>

/*
    |------------------------------------------------------------------|
    |             Bismillah Hir Rahman Nir Raheem                      |
    |------------------------------------------------------------------|
    |                                                                  |
    |           ░█▀▀▀█ ░█─░█ ─█▀▀█ ░█──░█ ░█─▄▀ ░█─░█                  |
    |           ─▀▀▀▄▄ ░█▀▀█ ░█▄▄█ ░█▄▄▄█ ░█▀▄─ ░█▀▀█                  |
    |           ░█▄▄▄█ ░█─░█ ░█─░█ ──░█── ░█─░█ ░█─░█                  |
    |                                                                  |
    |                                          Country:Bangladesh/EWU  |
    |                                          Problem:                |
    |------------------------------------------------------------------|
*/

#define sfi(n) scanf("%d", &n)
#define sf scanf
#define pf printf
#define sfl(n) scanf("%lld", &n)
#define sfd(n) scanf("%lf", &n)
#define sfi2(x, y) scanf("%d %d", &x, &y);
#define sfl2(x, y) scanf("%lld %lld", &x, &y);
#define sfd2(x, y) scanf("%lf %lf", &x, &y);
#define pfc(i) printf("Case %d:\n", i)
#define pfn(n) printf("%d\n", n)
#define pfdn(n) printf("%f\n", n)
#define pb push_back
#define bl printf("\n")
#define spc putchar(' ')
#define fli() freopen("in.txt","r",stdin)
#define flo() freopen("out.txt","w",stdout)
#define ll long long
#define ull unsigned long long
#define debug(x) cerr << #x << " : " << x << endl
#define fi first
#define se second
#define find puts("I am here")
#define repe(i, n, test) for(int i=n; i<=test; i++)
#define rep(i, n, test) for(int i=n; i<test; i++)
#define MOD 1000000007
#define EPS 1e-7
#pragma comment(linker, "/stack:20000000")
#define _CRT_SECURE_NO_WARNINGS
#define MAX 1000005
const long long inf = 1000000000LL;
const int i32_max = 2147483645;
using namespace std;

#define PAIR pair<int, int>
int dir_x[] = {-1,1,0,0};
int dir_y[] = {0,0,-1,1};
// Code starts from here

int rrm[1000000];
int mp[1000000];

int random_num(int a, int b, int m, int r){
    memset(mp, 0, sizeof(mp));
    rrm[0] = r;
    repe(i, 1, 100000){
        rrm[i] = (a * rrm[i-1] + b) % m;
        if(mp[rrm[i]]>0){
            return abs(mp[rrm[i]] - i);
        }
        mp[rrm[i]] = i;
    }
}

int main(){
//ios_base::sync_with_stdio(false);
//cin.tie(NULL);
//fli();
//flo();
    int a, b, m, r;
    sfi2(a, b); sfi2(m, r);

    pfn(random_num(a, b, m, r));

    return 0;
}

#include <cstdio>

int main(int argc, char* argv[]) {
	unsigned a, b, m, r;
	scanf("%d%d%d%d", &a, &b, &m, &r);
	unsigned buf[100000];
	buf[r] = 1;
	for (int i = 2; ; ++i)
		if (buf[r = (r * a + b) % m])
			return printf("%d\n", i - buf[r]), 0;
		else buf[r] = i;
}

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;

typedef long long int ll;
typedef struct pr {
	int a, b;
};

/* ��������� ����� */
int comp(const void *i, const void *j)
{
	if ((*(pr *)i).a != (*(pr *)j).a)
		return -((*(pr *)i).a - (*(pr *)j).a);
	else
		return -((*(pr *)i).b - (*(pr *)j).b);
}

int main()
{
	// freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout);
	int a, b, r, m;
	vector<int> v;
	cin >> a >> b >> m >> r;
	while (true) {
		r = (a * r + b) % m;
		cout << r << endl;
		for (int i = 0; i < v.size(); i++) {
			if (v[i] == r) {
				cout << v.size() - i;
				return 0;
			}
		}
		v.push_back(r);
	}
	return 0;
}

#include<iostream>
#include<stdio.h>
using namespace std;

#define MAX 1000000
long long num[MAX+1];
long long next[MAX+1];

int getnext(int t)
{
	int i=0, j =-1;
	next[0] = -1;
	while( t+i < MAX ) {
		if(j == -1 || num[i+t] == num[j+t]){
			++i;
			++j;
			next[i] = j;
		}else j = next[j];
	}

	int ans = i-next[i];
	if(i%ans == 0 && i != ans){
		cout << i - next[i] << endl;
		return 1;
	}
	return 0;
}

int main()
{
	long long a, b, m, r0;
	while( cin >> a >> b >> m >> r0) {
		num[0] = r0;
		for(int i=1; i<MAX; ++i)
			num[i] = (a*num[i-1]+b)%m;

		for(int i=MAX-10000; i<MAX; ++i)
			if (getnext(i)) break;

	}
	return 0;
}

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

template<typename T>
using ordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;

#define ll long long
#define ull unsigned long long
#define __   ios_base::sync_with_stdio(0);cin.tie();cout.tie();

string s,s1,s2,s3,s4,s5;
ll n,m,x,y,z;
ll arr[500010];
ll brr[500010];
vector<ll>v,v1;
set<ll>st;

void memset_ll(ll a[], ll v, ll n)
{
    for(ll i=0; i<n; i++)
        a[i]=v;
}

int compare(const void * a, const void * b)
{
    return ( *(ll*)a - *(ll*)b );
}
void q_sort(ll a[], ll n)
{
    qsort(a, n, sizeof(ll), compare);
}

ll is_prime(ll n)
{
    ll i,j,k=1;
    for(i=2; i<=n/2; i++)
    {
        if(n%i==0)
        {
            k=0;
            break;
        }
    }
    return k;
}

ll bsearch(ll arr[], ll l, ll r, ll x)
{
    if (r >= l)
    {
        ll mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return bsearch(arr, l, mid - 1, x);
        return bsearch(arr, mid + 1, r, x);
    }
    return -1;
}

static int compare1 (const void * a, const void * b)
{
    if (*(double*)a > *(double*)b)
        return 1;
    else if (*(double*)a < *(double*)b)
        return -1;
    else
        return 0;
}

void q_sort_d(double a[], ll n)
{
    qsort(a, n, sizeof(double), compare1);
}

string trans_upper(string ss)
{
    transform(ss.begin(),ss.end(),ss.begin(), ::toupper);
    return ss;
}

ll power(ll a, ll b)
{
    ll pow = 1;
    while ( b )
    {
        if ( b & 1 )
        {
            pow = pow * a;
            --b;
        }
        a = a*a;
        b = b/2;
    }
    return pow;
}

int main()
{
    __
    ll t,h,i,j,k,l,p,q,r;
    ll d=0,e=0,f=0,g=0;
    ll dd=0,uu=0,rr=0,lll=0;
    ll ans=0,sum=0,temp=0;
    ll x1,y1,x2,y2;

    double p1,p2,p3,p4,p5;
    double pp=0.0,ppp=1.0;
    double pi =3.141592654;

    cin>>x>>y>>z>>r;
    ll a[100000];
    if(r==0)
    {
        cout<<z;
        return 0;
    }
    a[0]=(x*r+y)%z;
    for(i=1; i<100000; i++)
    {
        r=a[i-1];
        a[i]=(x*r+y)%z;
    }
    for(k=1; k<100000; k++)
    {
        j=99999;
        if(a[j]==a[j-k]&&a[j-1]==a[j-1-k])
        {
            cout<<k;
            return 0;
        }
    }

return 0;
}

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
#include <vector>

using namespace std;

int main() {
    int a, b, m, r0;
    cin >> a >> b >> m >> r0;

    int cur = 1;
    vector<int> was(m);

    while (true) {
        ++cur;
        int r0 = (1LL*a*r0+b)%m;
        if (was[r0]) {
            cout << cur - was[r0] << endl;
            return 0;
        }
        was[r0] = cur;
    }

    return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <map>
#include <vector>
#include <cmath>
#include <climits>
#include <string>
#include <cctype>
#include <ctime>
#include <sstream>
#include <algorithm>
using namespace std;

#pragma region defines

typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
typedef pair<ll, ll> pll;
typedef pair<string, string> ss;
typedef vector<ss> vss;
typedef vector<ii> vii;
typedef vector<pll> vpll;
typedef pair<char, int> pci;
typedef vector<pci> vci;
#define PI 3.14159265358979
#define FOR(from, to, counter) for (int counter = from; counter < int(to); counter++)
#define FRQ(from, to, counter) for (int counter = from; counter <= int(to); counter++)
#define REP(to, counter) FOR(0, to, counter)
#define X first
#define Y second
#define eps 1E-9
inline vi ReadVI(int count) {vi arrayname(count); REP(count, i) cin >> arrayname[i]; return arrayname; };
#pragma endregion defines
const int MOD = 1000000007;

vii::iterator f(vii::iterator first, vii::iterator last, const int& value)
{
	for (;first!=last;first++)
		if ((*first).first == value ) break;
	return first;
}

int main(void)
{

#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	double beginTime=clock();
#endif
	int a, b, m, r0, r1; cin >> a >> b >> m >> r0;
	vii ost;
	REP(m, i)
	{
		r1 = (a*r0 + b)%m;
		auto it = f(ost.begin(), ost.end(), r1);
		if (it != ost.end())
			return cout << i-(*(it)).Y, 0;
		else ost.push_back(make_pair(r1, i));
		r0 = r1;
	}

#ifndef ONLINE_JUDGE
	double endTime=clock();
	printf("\n***Elapsed = %.5lf******",(endTime-beginTime)/CLOCKS_PER_SEC);
#endif
}

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#include <ctime>

using namespace std;

int arr[100005];
int cum[100005];

int main()
{
	int a, b, m, r0, ans;
	cin >> a >> b >> m >> r0;
	memset(arr, 0, sizeof arr);
	int cur = r0;
	arr[cur] = 1;
	int cur2;
	while(arr[cur] != 2)
	{
		cur2 = ((a * cur) + b) % m;
		arr[cur2]++;
		if(arr[cur2] == 2)
		{
			break;
		}
		cum[cur] = cur2;
		cur = cur2;
	}
	if(cur == cur2) cout << "1" << endl;
	else
	{
		while(cum[cur2] != cur)
		{
			cur2 = cum[cur2];
			++ans;
		}

		cout << ans + 2 << endl;
	}
}

#include <iostream>
using namespace std;
int main(){
    int a,b,m,r; cin>>a>>b>>m>>r;
    int d[100009]={0};
    d[r]=1;
    for (int i=2; i<=10; i++){
        int k = (r * a + b) %m;
        r=k;
        if (d[k]!=0){
            cout<<i-d[k];
            return 0;
        }
        d[k]=i;
    }

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<long long,null_type,less<long long>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
s.find_by_order(x) xth element in set
x.order_of_key(x) number of elements <x*/
#define ll long long
#define vi vector<int>
#define si set<int>
#define mii map<int,int>
#define pb push_back
#define pf push_front
#define pii pair<int,int>
#define extract_word(s)  stringstream str(s); while(str>>word)
#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define SET(s) cout<<fixed<<setprecision(s)
#define chotu 1000000007
#define set0(a) memset(a,0,sizeof(a))
#define endl "\n"
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define lower_string(s) transform(all(s),s.begin(),::tolower())
#define upper_string(s) transform(all(s),s.begin(),::toupper())
#define size(s) s.size()
template<class T> bool umin(T &a, T b) { return a > b ? (a = b, true) : false; }
template<class T> bool umax(T &a, T b) { return a < b ? (a = b, true) : false; }
template<typename T,typename U>
bool compare(T x,U y){return(abs(x-y)<=1e-9);}
const int N=(int)1e5+5;
vector<bool> freq(N,0);
void solve()
{
fastio
int a,b,m,r0;
cin>>a>>b>>m>>r0;
vi v;
int ini=r0;
v.pb(ini);
while(1)
{
	int push=(a*ini+b)%m;
	if(freq[push])
	{
		auto it=find(all(v),push);
		cout<<v.end()-it;
		return ;
	}
	freq[push]=1;
	v.pb(push);
	ini=push;
}
}
int main()
{
//code
fastio
int t;
t=1;
while(t--)
{
solve();
cout<<endl;
}
}

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

int main()
{
    //freopen("input.txt","r",stdin);
    int a,b,m,r,q[100000]={},ri,ans=0, f=0,ff=0,e;
    string s;
    cin>>a>>b>>m>>r;
    for(int i=0;i<10000;i++)
    {
        ri=(a*r+b)%m;
        r=ri;
        q[i]=ri;
        for(int j=0; j<i; j++)
        {
            if(q[i]==q[j]&&f==0) {e=q[i]; ans++; f=1;}
            if(ff==1&&q[i]==e) {cout<<ans; return 0;}
            if(q[i]==q[j]&&q[i]!=e) {ans++; f=1; ff=1;}
        }
    }
    cout<<ans;
    return 0;
}

#include <iostream>
#include <map>

using namespace std;

int main()
{
	long m,r0,r1,step=1;
	int a,b;
	cin >> a >> b >> m >> r0;
	map<long,long> buf;
	buf[r0] = 1;
	do
	{
		++step;
		r1 = (a*r0 + b)%m;
		if (buf.count(r1)) break;
		else buf[r1] = step;
		r0 = r1;
		cout << r1 << endl;
	} while (1);
	cout << step-buf[r1];
	getchar();getchar();
	return 0;
}

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include <vector>
#include <map>
#include <set>
#include <utility>
#include <deque>
#include <cmath>
#include <functional>
#include<iomanip>
using namespace std;
#define ll long long int

int main()
{
int a,b,m,r0,r[1002],i,j,count=0,f=0;
cin>>a>>b>>m>>r0;

r[0]=(a*r0+b)%m;
for(i=0;i<1000;i++)
{
r[i+1]=(a*r[i]+b)%m;
}
/*for(i=0;i<1000;i++)
{cout<<" "<<r[i];}*/
for(i=0;i<1000;i++)
{ for(j=i+1;j<1000;j++)
    {
        if(r[i]==r[j])
           {
            count=j-i;
            f=1;}
if(f==1)
break;
}

if(f==1)
break;
}
cout<<count<<endl;
}

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<unordered_map>
#include<fstream>
#include<vector>
#include<numeric>
#include<queue>
#include<map>
#include<set>
using namespace std;
#define ll long long
#define ld long double
#define ull unsigned long long
#define mp make_pair
#define pb push_back
#define ppb pop_back
#define fst first
#define snd second
#define sz(a) ((int)(a).size())
#define md 1000000007
#define inf 0x7fffffff
const int maxn=1000000+10;
const ll MOD=1000000000+9;
int a,b,m,r0,data,ans,vis[maxn];
int main(){
//	freopen("data.in","r",stdin);
//	freopen("data.out","w",stdout);
	cin>>a>>b>>m>>r0;
	data=r0;
	for(int i=1;i<=2*m;i++){
		data=(data*a+b)%m;
		if(i>m){
			if(vis[data]){
				ans=i-vis[data];
				break;
			}
			vis[data]=i;
		}
	}
	cout<<ans<<endl;
	return 0;
}

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

template<typename T>
using ordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;

#define ll long long
#define ull unsigned long long
#define __   ios_base::sync_with_stdio(0);cin.tie();cout.tie();

string s,s1,s2,s3,s4,s5;
ll n,m,x,y,z;
ll arr[500010];
ll brr[500010];
vector<ll>v,v1;
set<ll>st;

void memset_ll(ll a[], ll v, ll n)
{
    for(ll i=0; i<n; i++)
        a[i]=v;
}

int compare(const void * a, const void * b)
{
    return ( *(ll*)a - *(ll*)b );
}
void q_sort(ll a[], ll n)
{
    qsort(a, n, sizeof(ll), compare);
}

ll is_prime(ll n)
{
    ll i,j,k=1;
    for(i=2; i<=n/2; i++)
    {
        if(n%i==0)
        {
            k=0;
            break;
        }
    }
    return k;
}

ll bsearch(ll arr[], ll l, ll r, ll x)
{
    if (r >= l)
    {
        ll mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return bsearch(arr, l, mid - 1, x);
        return bsearch(arr, mid + 1, r, x);
    }
    return -1;
}

static int compare1 (const void * a, const void * b)
{
    if (*(double*)a > *(double*)b)
        return 1;
    else if (*(double*)a < *(double*)b)
        return -1;
    else
        return 0;
}

void q_sort_d(double a[], ll n)
{
    qsort(a, n, sizeof(double), compare1);
}

string trans_upper(string ss)
{
    transform(ss.begin(),ss.end(),ss.begin(), ::toupper);
    return ss;
}

ll power(ll a, ll b)
{
    ll pow = 1;
    while ( b )
    {
        if ( b & 1 )
        {
            pow = pow * a;
            --b;
        }
        a = a*a;
        b = b/2;
    }
    return pow;
}

int main()
{
    __
    ll t,h,i,j,k,l,p,q,r;
    ll d=0,e=0,f=0,g=0;
    ll dd=0,uu=0,rr=0,lll=0;
    ll ans=0,sum=0,temp=0;
    ll x1,y1,x2,y2;

    double p1,p2,p3,p4,p5;
    double pp=0.0,ppp=1.0;
    double pi =3.141592654;

    cin>>x>>y>>z>>r;
    ll a[100000];
    if(x==0||y==0)
    {
        cout<<1;
        return 0;
    }
    if(r==0)
    {
        cout<<z;
        return 0;
    }
    a[0]=(x*r+y)%z;
    for(i=1; i<100000; i++)
    {
        r=a[i-1];
        a[i]=(x*r+y)%z;
    }
    for(k=1; k<100000; k++)
    {
        j=99999;
        if(a[j]==a[j-k]&&a[j-1]==a[j-1-k])
        {
            cout<<k;
            return 0;
        }
    }

return 0;
}

#include <iostream>
#include <cstring>

using namespace std;

long long H[60001];

long long getNext(long long a, long long b, long long m, long long r0){
    return (a*r0 + b)%m;
}

int main(){
    long long a,b,m,r;
    cin >> a >> b >> m >> r;

    memset(H, 0, sizeof(H));

    long long i = 1;

    H[r] = i;

    while(1){
        i++;
        r = getNext(a,b,m,r);
        if (H[r]) break;
        H[r] = i;
    }

    cout << (i - H[r]) << endl;

    return 0;
}

#include<iostream>

using namespace std;

int main(){

    int Z,I,M,L;
    int x1,x2,n,m,caso;
        cin>>Z>>I>>M>>L;

        x1=L;
        x2=L;

        m=0;

        do{
            x1=(x1*Z+I)%M;
            x2=(x2*Z+I)%M;
            x2=(x2*Z+I)%M;
            m++;
        }while(x1!=x2);

        cout<<m;

    return 0;
}

#include <cstdlib>
#include <iostream>
#include<stdio.h>
using namespace std;

int main(int argc, char *argv[])
{
    int a,b,m,r0,r1,r2;
    int nums[20000]={ 0 };
    int times[20000]={ 0 };
    fscanf(stdin,"%d %d %d %d",&a,&b,&m,&r0);
    int i=0,time=0,res=0;
    nums[r0]=0;
    times[r0]=0;
    while (i==0) {
          time++;
          r1=(a*r0+b)%m;
          if (nums[r1]==1) {
              i=1;
              res=time-times[r1];
          }
          else{
               nums[r1]=1;
               times[r1]=time;
               r0=r1;
          }

    }
    fprintf(stdout,"%d \n",res);
}

#include<iostream>
#include<string>
using namespace std;
int t[100005];
int a,b,m,r[100005];
int cal(){
    bool vis[100005];
    int i=1;
    for(int i=1;i<=2*m;i++){
        r[i]=(a*r[i-1]+b+m)%m;
        //cout<<"r[i]: "<<r[i]<<endl;
        if(vis[r[i]])return i-t[r[i]];
        vis[r[i]]=1;
        t[r[i]]=i;
    }
    return 0;
}
int main(){
    while(cin>>a>>b>>m>>r[0]){
        cout<<cal()<<endl;
    }
}

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <string>
using namespace std;

int main(){
    int a,i,b,m,r[1000000],N;
    cin >> a >> b >> m >> r[0];
    int n[m];
    N = 0;
    for (i=0;i<=m;i++){
        n[i]=0;
    }

    for (i=1;i<=999999;i++){
        r[i]=(a*r[i-1]+b) % m;
        n[r[i]]+=1;
    }

    for (i=0;i<=m;i++){
        if (n[i] >= 30000){
           N++;
        }
    }

    cout << N;
}

#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
int mrSequence[210];

int ladyCheckCurrentSequencePosition(int mrSequenceIterator) {
    int mrCheckIterator;
    for (mrCheckIterator = 1; mrCheckIterator < mrSequenceIterator; mrCheckIterator++)
        if (mrSequence[mrSequenceIterator] == mrSequence[mrCheckIterator])
            if (mrSequence[mrCheckIterator] == mrSequence[mrSequenceIterator+mrSequenceIterator - mrCheckIterator])
            return (mrSequenceIterator - mrCheckIterator);
    return -1;
};

int main(int argc, char** argv) {
    int mrA; int mrB; int mrsM; int mrR0;
    int mrResult;
    int mrSequenceIterator;
    cin >> mrA; cin >> mrB; cin >> mrsM; cin >> mrR0;
    mrSequence[0]=mrR0;
    for (mrSequenceIterator = 1; mrSequenceIterator < 210; mrSequenceIterator++) {
        mrSequence[mrSequenceIterator] = ((mrA * mrSequence[mrSequenceIterator-1] + mrB) % mrsM);
    };
    for (mrSequenceIterator = 1; mrSequenceIterator < 210; mrSequenceIterator++) {
        mrResult = ladyCheckCurrentSequencePosition(mrSequenceIterator);
        if (mrResult > -1)
            break;
    };
    cout << mrResult;
    return 0;
};

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <cctype>
#include <cstring>
#include <string>

using namespace std;

typedef long long LL;
typedef unsigned long long uLL;

int vis[100005];

int main()
{
    int a,b,m,r0;
    cin>>a>>b>>m>>r0;
    int k=0;
    int r=r0;
    memset(vis,-1,sizeof(vis));
    int q=30;
    while(q--)
    {
        //printf("%d ",r);
        vis[r]=k;
        k++;
        r=(a*r+b)%m;
    }
    //printf("%d ",r);
    //cout<<endl;

    cout<<k-vis[r]<<endl;

	return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>
#include <inttypes.h>

using namespace std;

int main()
{
    const int64_t MAX = 100000;
    int64_t a, b, m, r_p, r_c;
    int64_t r[MAX] = {0};
    int64_t ans = 0;

    cin >> a >> b >> m >> r_p;

    for (int64_t i = 1; i <= MAX * 10; ++i) {
        r_c = (a * r_p + b) % m;
        r_p = r_c;
        r[r_c] += 1;
    }

    sort(r, r + MAX, greater<int64_t>());

    for (int64_t i = 0; i < MAX - 1; ++i)
        if ((r[i] + 1) / (r[i + 1] + 1) > 9) {
            ans = i + 1;
            break;
        }

    cout << ans;

    return 0;
}

#include "bits/stdc++.h"
#include "ext/pb_ds/assoc_container.hpp"
#include "ext/pb_ds/tree_policy.hpp"
using namespace __gnu_pbds;
using namespace std;

namespace basic{
    using ll =long long int;
    #define imax INT_MAX
    #define lmax LLONG_MAX
    #define pb push_back
    #define ld long double
    #define pii pair<int,int>
    #define pll pair<ll,ll>
    #define v vector
    #define vll vector<ll>
    #define vv(a) vector<vector<a>>
    #define cld complex<ld>
    #define cll complex<ll>
    #define all(x) (x).begin(),(x).end()
    #define rall(x) (x).rbegin(),(x).rend()
    #define mini(a) *min_element(all(a))
    #define maxi(a) *max_element(all(a))
    #define sum_vec(a) accumulate(all(a),0LL)
    #define trans_lower(s) transform(all(s),s.begin(),::tolower)
    #define trans_upper(s) transform(all(s),s.begin(),::toupper)
    #define sz(a) ((ll)a.size())
    #define Pi acos(-1)
    #define f first
    #define se second
    #define lb lower_bound
    #define ub upper_bound
    #define endl "\n"
    #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
    #define tc int t=0;cin>>t;while(t--)
    #define tc1 int t=1;while(t--)
    #define tc_case int t=0,a_t=0;cin>>t;a_t=t;while(t--)
    #define case(a) cout<<"Case #"<<a_t-t<<": "<<a<<endl;
    const ll inf = 1e9+7;
    template<class T>void refresh(T &a,ll n){
        assert(n>=0);
        a.clear();a.resize(n);
    }
    template<class X,class Y>void refresh_with_value(X &a,ll n,Y value){
        assert(n>=0);
        a.clear();a.resize(n,value);
    }
    template<class X>void Unique(X &a){
        sort(all(a));
        a.erase(unique(all(a)),a.end());
    }
    template<class T> ll uniq_size(T a){
        sort(all(a));
        return distance(a.begin(),unique(all(a)));
    }
    template<class T> void smin(T &a, T b) { a = min(a, b); }
    template<class T> void smax(T &a, T b) { a = max(a, b); }
    template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
}
using namespace basic;

namespace IO{
    void open(){
        ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
        #ifdef LOCAL
            freopen("C:\\Users\\ishan\\Coding_stuff\\CP\\Codeforces\\input.txt","r",stdin);
            freopen("C:\\Users\\ishan\\Coding_stuff\\CP\\Codeforces\\output.txt","w",stdout);
        #endif
    }
    void close(){
        #ifdef LOCAL
            cerr << "\nTime elapsed: "<<1000.00 * clock() / CLOCKS_PER_SEC <<" ms.\n";
        #endif
    }
    #ifdef LOCAL
        #define Debug(x) cout<<"ON LINE NUMBER:     "<<__LINE__<<"\t :--> \t"<<#x<<"   =   "<<x<<endl;
        int line=0;
        #define debug(args...){string _s=#args; replace(all(_s),',',' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); line=__LINE__; err(_it, args);}
        void err(istream_iterator<string> it){
            istream_iterator<string> qwertyuiop = it;
        }
        template<typename T, typename... Args>
        void err(istream_iterator<string> it, T a, Args... args){
            cout<<"ON LINE NUMBER:     "<<line<<"\t :--> \t"<<*it<<"   =   "<<a<<endl;
            err(++it, args...);
        }
    #else
        #define Debug(x)
        #define debug(args...)
    #endif
    template<class T>istream& operator >> (istream& cin,v<T> &a){
        for(auto &i:a)cin>>i;
        return cin;
    }
    istream& operator >> (istream& cin,pll &a){
        cin>>a.f;cin>>a.se;
        return cin;
    }
    istream& operator >> (istream& cin,pii &a){
        cin>>a.f;cin>>a.se;
        return cin;
    }
    template<class X,class Y>ostream& operator << (ostream& cout,pair<X,Y> &a){
        cout<<a.f<<" "<<a.se<<"\t";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,v<X> &a){
        for(auto i:a)cout<<i<<" ";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,vv(X) &a){
        for(auto &i:a){cout<<i<<endl;}
        return cout;
    }
    template<class X,class Y>ostream& operator << (ostream& cout,unordered_map<X,Y> &a){
        for(auto &i:a){cout<<i.f<<"\t"<<i.se<<endl;}
        return cout;
    }
    template<class X,class Y>ostream& operator << (ostream& cout,map<X,Y> &a){
        for(auto &i:a){auto curr=i.f;cout<<curr<<"\t"<<i.se<<endl;}
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,set<X> &a){
        for(auto i:a)cout<<i<<" ";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,multiset<X> &a){
        for(auto i:a)cout<<i<<" ";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,deque<X> &a){
        for(auto i:a)cout<<i<<" ";
        return cout;
    }
    template<class X>ostream& operator << (ostream& cout,priority_queue<X> a){
        while(!a.empty()) {
            auto q = a.top();
            cout << q << ' ';
            a.pop();
        }
        return cout;
    }
    template<class X , class Y, class Z>ostream& operator << (ostream& cout,priority_queue<X,Y,Z> a){
        while(!a.empty()) {
            auto q = a.top();
            cout << q << ' ';
            a.pop();
        }
        return cout;
    }
    void in(double& x){
        string t; cin >> t; x = stod(t);
    }
    void in(ld& x){
        string t; cin >> t; x = stold(t);
    }
    template<class T> void in(T& x){ cin>>x; }
    template<class X, class... Args> void in(X& first, Args&... rest) {
        in(first); in(rest...);
    }
    const int precision = 10;
    void out(ld& x) { cout << fixed << setprecision(precision) << x << '\n'; }
    template<class T> void out(T x) { cout << x << '\n'; }
    template<class Arg, class... Args> void out(Arg first,Args... rest) {
        cout << first << ' '; out(rest...);
    }
}
using namespace IO;

int main()
{
    open();

    ll a,b,m,r0;in(a,b,m,r0);
    map<ll,ll> mp;
    mp[r0] = 0;
    rep(i,1,100000) {
        r0 = (a * r0 + b) % m;
        if(mp[r0]) {
            out(i - mp[r0]);
            break;
        }
        mp[r0] = i;
    }

    close();
    return 0;
}

#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<vector>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

int main()
{
int i, j, k, n, a, b, m, r0, p, q, r;
int v[100006];
cin>>a>>b>>m>>r0;

k=1;
A:for(i=k;i<=16+k;i++)
{
    r0=(a*r0+b)%m;
    v[i]=r0;
    //cout<<v[i]<<" ";
}
//cout<<"i: "<<i<<"\n";
if(i>=50000)
{
cout<<m;
exit(0);
}
//cout<<"\n";
r=i-1;
p=k;
q=2*k;
while(v[p]!=v[q] && q<r)
{
    p++;
    q=2*p;
}
if(v[p]==v[q] && v[p+1]!=v[q])
{
    cout<<p;
    return 0;
}
else if(v[p]==v[q] && v[p+1]==v[q])
{
    cout<<"1";
    return 0;
}

else
{
    k=16+k+1;
    //cout<<k<<"\n";
    goto A;
}

return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>
#include <inttypes.h>

using namespace std;

int main()
{
    const int64_t MAX = 100000;
    int64_t a, b, m, r_p, r_c;
    int64_t r[MAX] = {0};
    int64_t ans = 0;

    cin >> a >> b >> m >> r_p;

    for (int64_t i = 1; i <= MAX * 50; ++i) {
        r_c = (a * r_p + b) % m;
        r_p = r_c;
        r[r_c] += 1;
    }

    sort(r, r + MAX, greater<int64_t>());

    for (int64_t i = 0; i < MAX - 1; ++i)
        if ((r[i] + 1) / (r[i + 1] + 1) > 40) {
            ans = i + 1;
            break;
        }

    cout << ans;

    return 0;
}

//#pragma GCC optimize("Ofast")
//#pragma GCC optimization ("O3")
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC target("avx,avx2,fma")
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define mod 1000000007
#define fi first
#define se second
#define pii pair<int,int>
//#define push_back emplace_back
//#define push emplace
//#define insert emplace
#define int long long
#define endl '\n'
#define pll pair<long long,long long>
#define LONGLONG_MAX 10000000000000000
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
long long power(long long a,long long b){
    long long ans=1;
    while(b>0){
        if(b&1){ans=(ans*a)%mod;}
                a=(a*a)%mod;
                b>>=1;
        }
    return ans;

}

int32_t main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int a,b,r,n;
	cin>>a>>b>>n>>r;
	int x[n]={0};
	int y=0;
	while(x[r]==0){
		y++;
		x[r]=1;
		r=a*r+b;
		r=r%n;
	}
	cout<<y;
	return 0;

}

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    bool visit[10000];
    int store[10000];
    int a,b,m,r0,mark;
    while(cin>>a>>b>>m>>r0)
    {
        memset(visit,false,sizeof(visit));
        store[0]=r0;
        for(int i=1;;i++)
          {
            store[i]=(a*store[i-1]+b)%m;
            if(visit[store[i]]==false)
                visit[store[i]]=true;
            else
            {
                mark=i;
                break;
            }
        }
        for(int j=1;j<mark;j++)
        {
            if(store[j]==store[mark])
            {
                cout<<mark-j<<endl;
                break;
            }
        }
    }
 }

#include<iostream>
#include<stdio.h>
using namespace std;
int r[500000];
int main()
{
	int a,b,m,t,pos1,pos2;
	bool flag=0;
	while(cin>>a>>b>>m>>t)
	{
		int cnt=0;
		t=(a*t+b)%m;

		for(int i=1;i<=1000;i++)
		{
			r[i]=t;
			t=(a*t+b)%m;
		}

		for(int i=1;i<=1000;i++)
		{
			flag=0;
			for(int j=1;j<i;j++)
			if(r[i]==r[j])
			{
				pos1=i;
				pos2=j;
				flag=1;
				break;
			}

			bool p=0;

			if(flag)
			{
				p=1;
				int f=pos1;
				for(int d=pos2;d<pos1;d++)
				{
					if(r[d]==r[f++])
					{
						cnt++;
					}
					else
					{
						p=0;
					    break;
					}
				}
			}

			if(p)
			{
			cout<<cnt<<endl;
			break;
			}
		}
	}
	return 0;
}

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <memory.h>
using namespace std;
long long a,b,m,r0;
long long first[10005];
int main()
{
    cin>>a>>b>>m>>r0;
    memset(first,-1,sizeof first);
    first[r0]=0;
    for (long long i=1;;i++)
    {
        r0=(r0*a+b)%m;
        if (first[r0]!=-1)
        {cout<<(i-first[r0])<<endl;break;}
        else
        {first[r0]=i;}
    }
}