#include <bits/stdc++.h>
using namespace std;
int has[2000005];
int main() {
  int a, b, m, r;
  cin >> a >> b >> m >> r;
  has[r] = 1;
  for (int i = 2;; i++) {
    r = (a * r + b) % m;
    if (has[r]) {
      cout << i - has[r];
      return 0;
    }
    has[r] = i;
  }
}
