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