#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, m, r;
  cin >> a >> b >> m >> r;
  int *arr = (int *)calloc(m, sizeof(int));
  int t = 0;
  while (arr[r] == 0) {
    t++;
    arr[r] = t;
    r = ((a * r) + b) % m;
  }
  cout << t - arr[r] + 1 << endl;
  return 0;
}
