#include <bits/stdc++.h>
int t[100005];
int main() {
  int a, b, m, r;
  scanf("%d%d%d%d", &a, &b, &m, &r);
  for (int i = 0; i <= m; i++) t[i] = -1;
  t[r] = 0;
  int r1 = 0;
  for (int i = 1; i <= m; i++) {
    r1 = (r * a + b) % m;
    if (t[r1] != -1) {
      printf("%d", i - t[r1]);
      return 0;
    }
    t[r1] = i;
    r = r1;
  }
  return 0;
}
