#include <bits/stdc++.h>
#pragma comment(linker, "/stack:64000000")
using namespace std;
const int MAX = 100000 + 10;
int p[MAX];
int main() {
  memset(p, -1, sizeof(p));
  int a, b, m, r;
  cin >> a >> b >> m >> r;
  p[r] = 0;
  for (int i = 1;; i++) {
    r = (a * r + b) % m;
    if (p[r] != -1) {
      cout << i - p[r];
      return 0;
    } else {
      p[r] = i;
    }
  }
  return 0;
}
