#include <bits/stdc++.h>
int a, b, m, r, cnt[100001], i;
int main() {
  scanf("%d %d %d %d", &a, &b, &m, &r);
  for (i = 0; i < m; i++) cnt[i] = 0;
  i = 0;
  while (cnt[(a * r + b) % m] == 0) {
    i++;
    r = (a * r + b) % m;
    cnt[r] = i;
  }
  printf("%d\n", i + 1 - cnt[(a * r + b) % m]);
  return 0;
}
