#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios_base::sync_with_stdio(false);
  int a, b, m, r;
  cin >> a >> b >> m >> r;
  map<int, int> s;
  s[r] = 0;
  for (int i = 1; i < 1123456; ++i) {
    r = (a * r + b) % m;
    if (s.count(r)) {
      cout << i - s[r];
      break;
    }
    s[r] = i;
  }
}
