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