#include <bits/stdc++.h>
using namespace std;
int main() {
  int f[100000] = {}, a, b, m, r;
  cin >> a >> b >> m >> r;
  f[r] = 1;
  for (int i = 2;; i++) {
    r = (a * r + b) % m;
    if (f[r]) {
      cout << i - f[r];
      break;
    } else
      f[r] = i;
  }
  return 0;
}
