#include <bits/stdc++.h>
using namespace std;
int arr[100020];
int func(int a, int b, int m, int r0) {
  memset(arr, -1, sizeof(arr));
  int stps = 0;
  while (true) {
    if (arr[r0] != -1) return stps - arr[r0];
    arr[r0] = stps++;
    r0 = (a * r0 + b) % m;
  }
}
int main() {
  int a, b, m, r0;
  cin >> a >> b >> m >> r0;
  cout << func(a, b, m, r0) << endl;
}
