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