#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000 * 141;
bool was[MAXN];
bool solve() {
  int a, b, m, cur;
  cin >> a >> b >> m >> cur;
  int ans = 0;
  while (!was[cur]) {
    was[cur] = true;
    cur = (a * cur + b) % m;
  }
  memset(was, 0, sizeof(was));
  while (!was[cur]) {
    ++ans;
    was[cur] = true;
    cur = (a * cur + b) % m;
  }
  cout << ans;
  return false;
}
int main() {
  while (solve())
    ;
  return 0;
}
