#include <bits/stdc++.h>
using namespace std;
int main() {
  int ultap[100005];
  memset(ultap, -1, sizeof ultap);
  int A, B, M, R;
  cin >> A >> B >> M >> R;
  int ite = 0;
  while (true) {
    ite++;
    R = (A * R + B) % M;
    if (ultap[R] != -1) break;
    ultap[R] = ite;
  }
  cout << ite - ultap[R] << endl;
  return 0;
}
