#include <bits/stdc++.h>
int main(void) {
  int a, b, m, r0, r, t[100000] = {0}, i, l = 0;
  scanf("%d %d %d %d", &a, &b, &m, &r0);
  for (i = 1, r = r0; !l; ++i) {
    if (t[r])
      l = i - t[r];
    else
      t[r] = i;
    r = (a * r + b) % m;
  }
  printf("%d\n", l);
  exit(EXIT_SUCCESS);
}
