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