#include <bits/stdc++.h>
bool flag[1000009];
int arr[1000009];
using namespace std;
int main() {
  int a, b, m, r, curr, cnt = 0;
  cin >> a >> b >> m >> r;
  arr[0] = r;
  flag[arr[0]] = 1;
  for (int i = 1; i < 1000009; i++) {
    arr[i] = (a * arr[i - 1] + b) % m;
    if (!flag[arr[i]]) {
      flag[arr[i]] = 1;
    } else {
      curr = i;
      break;
    }
  }
  for (int i = 0; i < 1000009; i++) {
    if (arr[curr] == arr[i]) {
      cout << curr - i << endl;
      return 0;
    }
  }
  return 0;
}
