#include <bits/stdc++.h>
using namespace std;
long long idx[150000];
int main() {
  long long a, b, m, r;
  cin >> a >> b >> m >> r;
  int id = 0;
  while (idx[r] == 0) {
    idx[r] = id;
    id++;
    r = (a * r + b) % m;
  }
  printf("%lld\n", id - idx[r]);
}
