#include <bits/stdc++.h>
int last[100009];
int main() {
  int a, b, m, r0;
  scanf("%d %d %d %d", &a, &b, &m, &r0);
  last[r0] = 1;
  int step = 2;
  while (1) {
    r0 = (a * r0 + b) % m;
    if (last[r0]) {
      printf("%d\n", step - last[r0]);
      return 0;
    }
    last[r0] = step++;
  }
}
