#include <bits/stdc++.h>
using namespace std;
long long memory[100000 + 1];
int main() {
  int a, b, m, r0;
  cin >> a >> b >> m >> r0;
  long long count = 0;
  while (1) {
    r0 = ((a * r0) + b) % m;
    if (memory[r0]) {
      break;
    }
    memory[r0] = ++count;
  }
  cout << count - memory[r0] + 1 << endl;
  return 0;
}
