#include <bits/stdc++.h>
using namespace std;
void solve();
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  solve();
}
void solve() {
  long long int m, a, b, r0;
  cin >> a >> b >> m >> r0;
  long long int pos[m + 1];
  memset(pos, -1, sizeof pos);
  long long int cnt = 0;
  long long int ri = r0;
  while (cnt != 2 * m) {
    ri = (a * ri + b) % m;
    if (pos[ri] != -1) {
      cout << cnt - pos[ri] << '\n';
      return;
    } else
      pos[ri] = cnt;
    cnt++;
  }
}
