#include <bits/stdc++.h>
using namespace std;
long long a, b, m, r0;
long long f(long long r) { return ((a * r + b + m) % m); }
long long calh(long long i, long long j) {
  i = f(i);
  j = f(f(j));
  while (i != j) {
    i = f(i);
    j = f(f(j));
  }
  j = r0;
  while (i != j) {
    i = f(i);
    j = f(j);
  }
  j = f(i);
  long long cnt = 1;
  while (j != i) {
    j = f(j);
    cnt++;
  }
  return cnt;
}
int main() {
  cin >> a >> b >> m >> r0;
  cout << calh(r0, r0);
  cout << endl;
  return 0;
}
