#include <bits/stdc++.h>
using namespace std;
const int INF = 1029384756;
const double PI = acos(-1);
const double EPS = 0.0000000304;
const int MAX = 123123;
int vt[MAX], vid;
int A, B, M, R0;
int main() {
  scanf("%d%d%d%d", &A, &B, &M, &R0);
  while (!vt[R0]) {
    vt[R0] = vid++;
    R0 = (R0 * A + B) % M;
  }
  printf("%d\n", vid - vt[R0]);
}
