#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, m, r0, period;
  cin >> a >> b >> m >> r0;
  map<int, int> freq;
  bool runme = true;
  int i = 0, count1 = 0, count2 = 0;
  while (runme) {
    int r1 = (a * r0 + b) % m;
    if (freq[r1] > 1) {
      period = i - freq[r1];
      freq[r1] = i;
      count2++;
    } else {
      freq[r1] = i;
      count1++;
    }
    if (count2 - count1 > 0) runme = false;
    r0 = r1;
    i++;
  }
  cout << period << endl;
  return 0;
}
