#include <bits/stdc++.h>
int main() {
  int m, a, b, r;
  unsigned long long tab[100010] = {0}, res, index = 1;
  scanf("%d", &a);
  scanf("%d", &b);
  scanf("%d", &m);
  scanf("%d", &r);
  tab[r] = 1;
  while (1) {
    index++;
    r = ((a * r + b) % m);
    if (tab[r] > 0) {
      res = index - tab[r];
      break;
    } else
      tab[r] = index;
  }
  printf("%I64u", res);
  return 0;
}
