#include <bits/stdc++.h>
using namespace std;
const long long INFLL = 1e18;
int main() {
  int v[100010] = {};
  int a, b, c, d;
  cin >> a >> b >> c >> d;
  v[d] = 1;
  for (int i = 2; i < 2 * 100010; i++) {
    d = (a * d + b) % c;
    if (v[d] != 0) {
      cout << i - v[d] << endl;
      return 0;
    }
    v[d] = i;
  }
  return 0;
}
