#include <bits/stdc++.h>
using namespace std;
inline double sqr(double x) { return x * x; }
#pragma comment(linker, "/STACK:16777216")
int x[100000], a, b, m, r, i = 1;
int main() {
  cin >> a >> b >> m >> r;
  while (!x[r]) {
    x[r] = i++;
    r = (a * r + b) % m;
  }
  cout << i - x[r];
  return 0;
}
