#include <bits/stdc++.h>
using namespace std;
bool mark[100005];
int x[100005];
int main() {
  int b, c, d, a;
  cin >> b >> c >> d >> a;
  x[0] = a;
  int i = 0;
  while (!mark[x[i]]) {
    i++;
    x[i] = (b * x[i - 1] + c) % d;
    mark[x[i - 1]] = true;
  }
  for (int j = 0; j < i; j++)
    if (x[j] == x[i]) {
      cout << i - j << endl;
      return 0;
    }
  return 0;
}
