#include <bits/stdc++.h>
bool hash[111111];
int a, b, m;
int r[111111];
int main() {
  scanf("%d %d %d %d", &a, &b, &m, &r[0]);
  int el = -1;
  int N = 0;
  for (int i = 1; i < 111111; i++) {
    r[i] = (a * r[i - 1] + b) % m;
    if (hash[r[i]] == true) {
      el = r[i];
      N = i;
      break;
    } else {
      hash[r[i]] = true;
    }
  }
  int lung;
  for (int i = 1; i < N; i++) {
    if (r[i] == el) {
      lung = N - i;
      printf("%d\n", N - i);
      break;
    }
  }
  return 0;
}
