#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, m, r, i;
  cin >> a >> b >> m >> r;
  vector<bool> OK(m + 1, false);
  vector<int> R;
  R.push_back(r);
  OK[r] = true;
  while (1) {
    r = (a * r + b) % m;
    R.push_back(r);
    if (OK[r]) break;
    OK[r] = true;
  }
  for (i = 0; i < R.size(); i++)
    if (R[i] == r) break;
  cout << R.size() - i - 1 << endl;
  return 0;
}
