#include <bits/stdc++.h>
using namespace std;
int main() {
  long long a, b, m, r0;
  cin >> a >> b >> m >> r0;
  int step = 0;
  map<int, int> smap;
  smap[r0] = 0;
  while (true) {
    r0 = r0 * a + b;
    r0 %= m;
    step++;
    if (smap.find(r0) != smap.end()) {
      cout << step - smap[r0];
      break;
    }
    smap[r0] = step;
  }
  return 0;
}
