#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long a, b, m, r;
  cin >> a >> b >> m >> r;
  long long count = 0;
  unordered_set<long long> s;
  map<long long, long long> time;
  long long prev = ((a % m * r % m) % m + b % m) % m;
  s.insert(prev);
  time[prev] = 0;
  long long min_time = 999999;
  while (s.find(((a % m * prev % m) % m + b % m) % m) == s.end()) {
    count++;
    s.insert(((a % m * prev % m) % m + b % m) % m);
    prev = ((a % m * prev % m) % m + b % m) % m;
    time[prev] = count;
  }
  auto target = *s.find(((a % m * prev % m) % m + b % m) % m);
  cout << count - time[target] + 1 << endl;
}
int32_t main() {
  long long testcases = 1;
  while (testcases--) {
    solve();
  }
  return 0;
}
