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