#include <bits/stdc++.h>
int mas[111111] = {0};
using namespace std;
int main() {
  int a, b, r, m, n, t = 0;
  cin >> a >> b >> m >> r;
  while (1) {
    t++;
    r = (a * r + b) % m;
    if (mas[r]) break;
    mas[r] = t;
  }
  cout << t - mas[r];
}
