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