#include <bits/stdc++.h>
using namespace std;
int main() {
  long long _1 = 1, _2 = 2, _2231312313123213 = 1, _1312312321312 = 1;
  long long dizi[100002], cnt[100002] = {0}, i = 1, a, b, c;
  cin >> a >> b >> c >> dizi[0];
  cnt[dizi[0]] = 1;
  while (1) {
    dizi[i] = (dizi[i - 1] * a + b) % c;
    if (cnt[dizi[i]]) {
      cout << i - cnt[dizi[i]] + 1 << endl;
      return 0;
    } else
      cnt[dizi[i]] = i + 1;
    i++;
  }
  return 0;
}
