#include <bits/stdc++.h>
time_t waktu = clock();
void gettime() {
  printf("\nTime : %.2lf", (clock() - waktu) / double(CLOCKS_PER_SEC));
}
bool comp(int a, int b) { return (a > b); }
using namespace std;
int main() {
  int a, b, m, r, cek[100005] = {}, hasil = 0;
  scanf("%d %d %d %d", &a, &b, &m, &r);
  do {
    r = ((a * r) + b) % m;
    cek[r]++;
    if (cek[r] == 2) hasil++;
  } while (cek[r] != 3);
  printf("%d", hasil);
  return 0;
}
