#include <bits/stdc++.h>
using namespace std;
int a, b, m, x, fx;
int f[100000];
bool s[100000];
int main() {
  cin >> a >> b >> m >> x;
  while (s[x] == 0) {
    s[x] = 1;
    x = (a * x + b) % m;
  }
  fx = x;
  int i = 1;
  x = (a * x + b) % m;
  for (; x != fx; i++) {
    x = (a * x + b) % m;
  }
  cout << i;
}
