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