#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:256000000")
using namespace std;
template <class T>
double sqrt(T x) {
  return sqrt((double)x);
}
template <class T>
T sqr(T x) {
  return x * x;
}
const double PI = acos(-1.0);
const int INF = 1000000000;
const int MOD = 1000000007;
int main() {
  double TIME_START = clock();
  int a, b, m, r0, i = 0;
  cin >> a >> b >> m >> r0;
  vector<int> f(m, -1);
  while (f[r0] == -1) {
    f[r0] = i;
    r0 = (a * r0 + b) % m;
    i++;
  }
  cout << i - f[r0];
  fprintf(stderr, "\n\n%.15lf\n\n",
          (double)(clock() - TIME_START) / CLOCKS_PER_SEC);
  return 0;
}
