#include <bits/stdc++.h>
using namespace std;
int a, b, m, x, i;
int vis[100005];
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  memset(vis, 0, sizeof(vis));
  cin >> a >> b >> m >> x;
  for (i = 1; !vis[(a * x + b) % m]; i++)
    vis[(a * x + b) % m] = i, x = (a * x + b) % m;
  cout << i - vis[(a * x + b) % m];
  return 0;
}
