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