#include <bits/stdc++.h>
using namespace std;
int main() {
  long long a, b, m, r0;
  cin >> a >> b >> m >> r0;
  long long pper, per;
  vector<int> u(m, -1);
  long long r = r0;
  for (int it = 0;; ++it) {
    if (u[r] != -1) {
      pper = u[r];
      per = it - u[r];
      break;
    }
    u[r] = it;
    r = (a * r + b) % m;
  }
  cout << per << endl;
  return 0;
}
