#include <bits/stdc++.h>
using namespace std;
int A[100005], s;
int main() {
  int a, b, m, r;
  cin >> a >> b >> m >> r;
  for (; !A[r]; r = (r * a + b) % m) A[r] = ++s;
  cout << (s - A[r] + 1);
  return 0;
}
