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