#include <bits/stdc++.h>
const int INF = 1e9;
using namespace std;
long long a, b, m, r0;
int indexes[1000000];
int main() {
  for (int i = 0; i < (int)1000000; ++i) indexes[i] = -1;
  cin >> a >> b >> m >> r0;
  int cur = r0;
  for (int i = 0; i < 200000; ++i) {
    if (indexes[cur] != -1) {
      printf("%d\n", i - indexes[cur]);
      break;
    }
    indexes[cur] = i;
    cur = (a * cur + b) % m;
  }
  return 0;
}
