#include <bits/stdc++.h>
int main() {
  int a, b, m, r;
  scanf("%d%d%d%d", &a, &b, &m, &r);
  int* x = new int[100001];
  for (int i = 0; i < 100001; ++i) x[i] = -1;
  int c = 0;
  while (x[r] < 0) {
    x[r] = c;
    ++c;
    r = (a * r + b) % m;
  }
  printf("%d\n", c - x[r]);
  return 0;
}
