#include <bits/stdc++.h>
using namespace std;
bool point_left_from_line(long long x1, long long x2, long long poix,
                          long long y1, long long y2, long long poiy) {
  return (poix - x1) * (y2 - y1) < (poiy - y1) * (x2 - x1);
}
bool point_on_line(long long x1, long long x2, long long poix, long long y1,
                   long long y2, long long poiy) {
  return (poix - x1) * (y2 - y1) == (poiy - y1) * (x2 - x1);
}
long long ll_sign_0(long long x) {
  if (x < 0) return -1;
  if (x > 0) return 1;
  if (x == 0) return 0;
}
int main() {
  map<long long, vector<long long> > f;
  long long a, b, m, r, t;
  cin >> a >> b >> m >> r;
  long long buf = (a * r + b) % m;
  f[buf].push_back(1);
  int i = 1;
  buf = (a * buf + b) % m;
  while (f[buf].empty()) {
    f[buf].push_back(++i);
    buf = (a * buf + b) % m;
  }
  t = i + 1 - f[buf].back();
  cout << t << endl;
  return 0;
}
