#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:256000000")
using namespace std;
int main() {
  int a, b, m, r0;
  cin >> a >> b >> m >> r0;
  int c[100013];
  memset(c, 255, sizeof(c));
  c[r0] = 0;
  while (true) {
    int t = (a * r0 + b) % m;
    if (c[t] >= 0) {
      cout << c[r0] - c[t] + 1;
      return 0;
    }
    c[t] = c[r0] + 1;
    r0 = t;
  }
  return 0;
}
