#include <bits/stdc++.h>
using namespace std;
void openfiles() {}
bool solve() {
  int a, b, m, r0;
  scanf("%d %d %d %d ", &a, &b, &m, &r0);
  vector<int> visited(m, 0);
  int r = r0;
  int n = 0;
  while (visited[r] == 0) {
    n++;
    visited[r] = n;
    r = (a * r + b) % m;
  }
  printf("%d\n", n - visited[r] + 1);
  return false;
}
int main() {
  openfiles();
  while (solve())
    ;
  return 0;
}
