#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, m, r0, r, index = 0;
  cin >> a >> b >> m >> r0;
  int t[100001] = {0};
  r = r0;
  while (true) {
    ++index;
    if (t[r] != 0) {
      cout << index - t[r];
      return 0;
    }
    t[r] = index;
    r = (r * a + b) % m;
  }
  return 0;
}
