#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, m, x[100007], i, j, visit[100007], c, ans, cou = 0;
  memset(visit, 0, sizeof(visit));
  cin >> a >> c >> m >> x[0];
  for (i = 1; i <= m + 1; i++) {
    x[i] = (a * x[i - 1] + c) % m;
  }
  for (i = 1; i <= m + 1; i++) {
    if (visit[x[i]] == 0) {
      cou++;
      visit[x[i]] = cou;
    } else if (visit[x[i]] > 0) {
      cou++;
      ans = cou - visit[x[i]];
      break;
    }
  }
  cout << ans << "\n";
  return 0;
}
