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