#include <bits/stdc++.h>
using namespace std;
map<int, int> was;
int main() {
  int m, a, b, r0;
  cin >> a >> b >> m >> r0;
  int tek = 1;
  was[r0] = 1;
  while (true) {
    int t = (a * r0 + b) % m;
    tek++;
    if (was[t]) {
      cout << tek - was[t] << endl;
      return 0;
    }
    r0 = t;
    was[t] = tek;
  }
  return 0;
}
