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