#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const long long MOD = 1e9 + 7;
long double EPS = 1e-12;
const long long INF32 = 0x3F3F3F3F;
const long long INF = 0x3F3F3F3F3F3F3F3F;
const long long crng = rng();
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ifstream fin("input.txt");
  ofstream fout("output.txt");
  {
    long long a, b, m, r0;
    cin >> a >> b >> m >> r0;
    long long st[m];
    memset(st, -1, sizeof(st));
    st[r0] = 0;
    long long prv = r0;
    for (long long i = 1; i <= m; i++) {
      long long here = (a * prv + b) % m;
      if (st[here] != -1) return cout << i - st[here] << '\n', 0;
      st[here] = i, prv = here;
    }
  }
}
