#include <bits/stdc++.h>
using namespace std;
int main(int argc, const char* argv[]) {
  int a;
  cin >> a;
  int b;
  cin >> b;
  int m;
  cin >> m;
  int r0;
  cin >> r0;
  vector<int> r;
  r.push_back(r0);
  for (int i = 0; i < m; ++i) r.push_back((a * r[i] + b) % m);
  for (int i = 0; i < r.size() - 1; ++i) {
    bool flag = false;
    for (int j = i + 1; j < r.size(); ++j) {
      if (r[i] == r[j]) {
        cout << j - i;
        flag = true;
        break;
      }
    }
    if (flag) break;
  }
}
