#include <bits/stdc++.h>
using namespace std;
int last[100001];
int was[100001];
int main() {
  memset(was, 0, sizeof(was));
  int a, b, m, r;
  cin >> a >> b >> m >> r;
  int i = 0;
  while (true) {
    if (was[r] == 2) {
      cout << i - last[r] << endl;
      return 0;
    }
    last[r] = i;
    was[r]++;
    r = (a * r + b) % m;
    i++;
  }
  return 0;
}
