#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using str = string;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using pd = pair<ld, ld>;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<ld>;
using vs = vector<str>;
using vpi = vector<pi>;
using vpl = vector<pl>;
using vpd = vector<pd>;
const int MIN = 2e5 + 20;
const int MAX = 1e9 + 20;
map<ll, ll> m;
ll t, n, k, d, mn, a, r, mx, i, b, c, l, p, s;
int main() {
  cin >> a >> b >> n >> r;
  k = 1;
  while (1) {
    r = (r * a + b) % n;
    if (m[r]) {
      cout << k - m[r];
      return 0;
    } else
      m[r] = k;
    k++;
  }
}
