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