#include <bits/stdc++.h>
using namespace std;
int main(int argc, char **argv) {
  ios_base::sync_with_stdio(false);
  int a, b, m, r, i = 1;
  cin >> a >> b >> m >> r;
  int seq[100005];
  memset(seq, -1, sizeof(seq));
  seq[r] = 0;
  while (true) {
    r = (a * r + b) % m;
    if (seq[r] != -1) {
      cout << i - seq[r] << endl;
      break;
    }
    seq[r] = i++;
  }
  return 0;
}
