#include <bits/stdc++.h>
using namespace std;
int main() {
  bool f[100001] = {0};
  int s[100001], i, a, b, m, r0, r1, k = 0;
  cin >> a >> b >> m >> r0;
  f[r0] = 1;
  s[r0] = k++;
  while (1) {
    r1 = (a * r0 + b) % m;
    if (f[r1]) break;
    f[r1] = 1;
    s[r1] = k++;
    r0 = r1;
  }
  cout << k - s[r1];
  return 0;
}
