#include <bits/stdc++.h>
using namespace std;
int f[100005];
int main() {
  int a, b, m, x, i;
  cin >> a >> b >> m >> x;
  i = 1;
  while (1) {
    x = (a * x + b) % m;
    if (f[x]) {
      cout << i - f[x];
      return 0;
    }
    f[x] = i;
    i++;
  }
}
