#include <bits/stdc++.h>
using namespace std;
int a, b, m, x;
int vis[100005], f[100005];
int main() {
  cin >> a >> b >> m >> x;
  for (int i = 1;; i++) {
    x = (x * a + b) % m;
    vis[x]++;
    if (vis[x] == 1)
      f[x] = i;
    else {
      cout << i - f[x] << endl;
      return 0;
    }
  }
}
