#include <bits/stdc++.h>
using namespace std;
long long a, b, m, r;
long long f[100001];
int main() {
  cin >> a >> b >> m >> r;
  f[r] = 1;
  for (int t = 2; t <= 2 * m; t++) {
    r = (a * r + b) % m;
    if (f[r] != 0) {
      cout << t - f[r] << endl;
      return 0;
    }
    f[r] = t;
  }
  return 0;
}
