#include <bits/stdc++.h>
using namespace std;
int p[100100];
int main() {
  int a, b, m, r0;
  scanf("%d%d%d%d", &a, &b, &m, &r0);
  int x = 1;
  while (p[r0] == 0) {
    p[r0] = x;
    r0 = ((r0 * a) % m + b) % m;
    x++;
  }
  printf("%d\n", x - p[r0]);
  return 0;
}
