#include <bits/stdc++.h>
using namespace std;
string getLine(istream& stream) {
  string res;
  getline(stream, res);
  return res;
}
vector<string> getLineFields(istream& stream) {
  string line = getLine(stream);
  stringstream str;
  str << line;
  vector<string> fields;
  string temp;
  while (str >> temp) {
    fields.push_back(temp);
  }
  return fields;
}
template <typename T>
T str2type(string a) {
  stringstream t;
  t << a;
  T b;
  t >> b;
  return b;
}
int main() {
  int a, b, m, r0;
  cin >> a >> b >> m >> r0;
  map<int, int> seen;
  int nextr = r0;
  int index = 0;
  while (seen.find(nextr) == seen.end()) {
    seen[nextr] = index;
    nextr = (a * nextr + b) % m;
    ++index;
  }
  cout << index - seen[nextr] << endl;
  return 0;
}
