#include <bits/stdc++.h>
using namespace std;
int arr[100005];
int cum[100005];
int main() {
  int a, b, m, r0, ans = 0;
  cin >> a >> b >> m >> r0;
  memset(arr, 0, sizeof arr);
  int cur = r0;
  int cur2;
  int s, e;
  while (arr[cur] != 2) {
    cur2 = ((a * cur) + b) % m;
    arr[cur2]++;
    if (arr[cur2] == 2) {
      s = cur2;
      e = cur;
      break;
    }
    cum[cur] = cur2;
    cur = cur2;
  }
  if (s == e)
    cout << "1" << endl;
  else {
    while (cum[s] != e) {
      s = cum[s];
      ++ans;
    }
    cout << ans + 2 << endl;
  }
}
