#include <bits/stdc++.h>
using namespace std;
int occ[100000];
int main() {
  memset(occ, -1, sizeof occ);
  int a, b, r0, m;
  cin >> a >> b >> m >> r0;
  occ[r0] = 0;
  int prev = r0, r;
  int ans;
  for (int i = 1; i <= m; ++i) {
    r = prev * a + b;
    r %= m;
    if (occ[r] != -1) {
      ans = i - occ[r];
      break;
    }
    occ[r] = i;
    prev = r;
  }
  cout << ans << endl;
  return 0;
}
