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