#include <bits/stdc++.h>
using namespace std;
int F[1000005];
int a, b, m, r0, t, r2, r1, i;
int main() {
  cin >> a >> b >> m >> r0;
  F[r0] = 0;
  r1 = r0;
  for (i = 1; i <= m + 2; i++) {
    r2 = (int)((a * r1 + b) % m);
    if (F[r2] != 0) {
      t = i - F[r2];
      break;
    }
    F[r2] = i;
    r1 = r2;
  }
  cout << t << endl;
}
