#include <bits/stdc++.h>
using namespace std;
int main() {
  int sr[100099], a, b, r, m, pr, i, p = 0;
  cin >> a >> b >> m >> r;
  for (i = 1; i <= m + 2; i++) {
    sr[i] = 0;
  }
  for (i = 1; i <= m + 2; i++) {
    p = (a * r + b) % m;
    if (sr[p] > 0) {
      cout << i - sr[p] << endl;
      return 0;
    } else {
      sr[p] = i;
    }
    r = p;
  }
  cout << 0 << endl;
  return 0;
}
