#include <bits/stdc++.h>
using namespace std;
void solve() {
  int a, b, m, r0;
  cin >> a >> b >> m >> r0;
  unordered_set<int> s;
  int result = ((a * r0) + b) % m;
  s.insert(result);
  vector<int> v;
  v.push_back(result);
  int ans;
  while (true) {
    result = ((a * v.back()) + b) % m;
    if (s.count(result) == 1) {
      ans = v.size() - (find(v.begin(), v.end(), result) - v.begin());
      break;
    }
    s.insert(result);
    v.push_back(result);
  }
  cout << ans << "\n";
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  solve();
  return 0;
}
