#include <bits/stdc++.h>
using namespace std;
int main() {
  long long a, b, m, r, num, i;
  vector<int> v(100005, -1);
  cin >> a >> b >> m >> r;
  r = num = (a * r + b) % m;
  v[num] = i = 1;
  while (true) {
    i++;
    r = num = (a * r + b) % m;
    if (v[num] != -1) break;
    v[num] = i;
  }
  cout << i - v[num] << endl;
}
