#include <bits/stdc++.h>
using namespace std;
const int INF = (int)2e9;
const double EPS = 1e-6;
const double PI = 3.1415926535;
const int MOD = 1000003;
int last[100000];
int main() {
  int a, b, m, now, i = 2;
  cin >> a >> b >> m >> now;
  last[now] = 1;
  while (1) {
    now = (a * now + b) % m;
    if (last[now]) {
      cout << i - last[now];
      return 0;
    } else
      last[now] = i++;
  }
}
