#include <bits/stdc++.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;
  ans = m;
  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] == 0 || r[i] / r[i + 1] > 3) {
      ans = i + 1;
      break;
    }
  cout << ans;
  return 0;
}
