#include <bits/stdc++.h>
using namespace std;
int mod[100005];
int main() {
  int m, a, b, r, i;
  scanf("%d %d %d %d", &a, &b, &m, &r);
  mod[r] = 1;
  i = 2;
  while (1) {
    if (mod[(a * r + b) % m]) {
      cout << i - mod[(a * r + b) % m];
      return 0;
    }
    r = (a * r + b) % m;
    mod[r] = i;
    i++;
  }
  return 0;
}
