#include <bits/stdc++.h>
using std::cin;
using std::cout;
using std::endl;
using std::max;
using std::min;
using std::pair;
using std::set;
using std::string;
using std::swap;
using std::vector;
int main() {
  long long a, b, m, r0, per;
  cin >> a >> b >> m >> r0;
  vector<long long> mas(100100, -1);
  mas[r0] = 0;
  long long i = 1;
  while (1) {
    r0 = (r0 * a + b) % m;
    if (mas[r0] == -1) {
      mas[r0] = i;
    } else {
      per = i - mas[r0];
      break;
    }
    i++;
  }
  cout << per;
  return 0;
}
