#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b;
  long m, r0, k;
  vector<int> str;
  cin >> a >> b >> m >> r0;
  for (int i = 0; i < 10000000; ++i) {
    r0 = (r0 * a + b) % m;
    str.push_back(r0);
  }
  int i = 0, j = 1;
  for (i = 0; i < 10000000; ++i) {
    for (j; j < 10000000; ++j) {
      if (str[i] == str[j]) {
        k = j - i;
        goto M;
      }
    }
    j = i + 2;
  }
M:
  cout << k << endl;
}
