#include <bits/stdc++.h>
using namespace std;
int a, b, m, r, rp, x, p[100005];
int main() {
  while (~scanf("%d%d%d%d", &a, &b, &m, &rp)) {
    memset(p, 0, sizeof(p));
    x = 0;
    p[rp] = x++;
    while (1) {
      r = (a * rp + b) % m;
      if (p[r]) {
        printf("%d\n", x - p[r]);
        break;
      }
      p[rp = r] = x++;
    }
  }
}
