#include <bits/stdc++.h>
using namespace std;
int was[100000];
int main() {
  int a, b, m, r0;
  scanf("%d%d%d%d", &a, &b, &m, &r0);
  int k = 0;
  int r = r0;
  while (!was[r]) {
    was[r] = ++k;
    r = (a * r + b) % m;
  }
  printf("%d", k - was[r] + 1);
}
