#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int met[maxn];
int main() {
  memset(met, -1, sizeof met);
  int a, b, m, r;
  cin >> a >> b >> m >> r;
  int i;
  for (i = 0; met[r] == -1; ++i) {
    met[r] = i;
    r = (a * r + b) % m;
  }
  cout << i - met[r] << endl;
  return 0;
}
