#include <bits/stdc++.h>
using namespace std;
int main() {
  int i, j, k;
  int N, M, t, n, m, s;
  int a, b, r;
  cin >> a >> b >> m >> r;
  map<int, int> Map;
  int Count = 0;
  while (1) {
    Count++;
    r = (a * r + b) % m;
    if (Map[r]) {
      cout << Count - Map[r] << endl;
      return 0;
    } else
      Map[r] = Count;
  }
  return 0;
}
