#include <bits/stdc++.h>
int main(void) {
  int n, a, b, m, r, *app;
  scanf("%d %d %d %d", &a, &b, &m, &r);
  app = (int *)calloc(m, sizeof(int));
  for (n = 1; 1; n++) {
    r = (a * r + b) % m;
    if (app[r]) {
      printf("%d\n", n - app[r]);
      break;
    } else
      app[r] = n;
  }
  return 0;
}
