#include <bits/stdc++.h>
using namespace std;
const double pi = 3.141592653589793;
const int INF = 2000000000;
const int mod = 1000000007;
int main() {
  bool q[100005];
  memset((q), 0, sizeof((q)));
  int a, b, m, r0, r;
  cin >> a >> b >> m >> r0;
  r = r0;
  int left, right;
  int x;
  for (int i = 0;; i++) {
    r = (a * r + b) % m;
    if (!q[r])
      q[r] = 1;
    else {
      x = r;
      right = i;
      break;
    }
  }
  for (int i = 0;; i++) {
    r0 = (a * r0 + b) % m;
    if (r0 == x) {
      left = i;
      break;
    }
  }
  cout << right - left;
}
