#include <bits/stdc++.h>
using std::cin;
using std::cout;
const int N = 1e5 + 1;
int r, a, b, m, las[N];
int main() {
  cin >> a >> b >> m >> r;
  memset(las, -1, sizeof las);
  las[r] = 0;
  for (int i = 1;; ++i) {
    r = (a * r + b) % m;
    if (~las[r]) {
      cout << i - las[r];
      return 0;
    }
    las[r] = i;
  }
  return 0;
}
