#include <bits/stdc++.h>
using namespace std;
int r, a, b, m, useed[100000], p;
int main() {
  cin >> a >> b >> m >> r;
  while (useed[(a * r + b) % m] == 0) {
    useed[(a * r + b) % m] = 1;
    r = (a * r + b) % m;
  }
  int r1 = r;
  while (((a * r + b) % m) != r1) {
    r = (a * r + b) % m;
    p++;
  }
  p++;
  cout << p;
}
