#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:60000000")
using namespace std;
template <class T>
T sqr(T x) {
  return x * x;
}
double const pi = 3.1415926535897932384626433832795;
int const inf = (int)1e9;
long long const inf64 = (long long)4e18;
const string name = "b";
const int NMAX = 101001;
int a, b, m, r[2 * NMAX], used[2 * NMAX];
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;
}
