#include <bits/stdc++.h>
const int INF = 1000000;
using namespace std;
int main() {
  int a, b, m;
  vector<int> r(1);
  scanf("%d %d %d %d", &a, &b, &m, &r[0]);
  for (int i = 1; i < 2 * m + 2; i++) {
    r.push_back((a * r[i - 1] + b) % m);
  }
  vector<int> ans(2 * m + 2, INF);
  int res = 1;
  for (int i = 1; i < m + 1; i++) {
    for (int t = 1; t < m + 1; t++)
      if (r[i] == r[i + t]) {
        ans[i] = min(t, ans[i - 1]);
        res = ans[i];
        cout << res;
        return 0;
      }
  }
  cout << res;
  return 0;
}
