#include <bits/stdc++.h>
using namespace std;
int f(int a, int b, int m, int num) { return (a * num + b) % m; }
int main() {
  int a, b, m, r;
  scanf("%d%d%d%d", &a, &b, &m, &r);
  int k = 0;
  int num = m + 1;
  int cont = 0;
  int aux = f(a, b, m, r);
  while (1) {
    aux = f(a, b, m, aux);
    if (k == m) {
      num = aux;
      k++;
      continue;
    }
    if (k > m) {
      cont++;
      if (num == aux) break;
    }
    k++;
  }
  printf("%d\n", cont);
}
