#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1000000007;
const long long int N = 1e5 + 5;
long long int dp[N];
int32_t main() {
  memset(dp, -1, sizeof(dp));
  long long int a, b, m, r;
  cin >> a >> b >> m >> r;
  dp[r] = 0;
  long long int tmp = r;
  for (long long int i = 1;; i++) {
    tmp = (a * tmp + b) % m;
    if (dp[tmp] != -1) {
      cout << i - dp[tmp];
      return 0;
    }
    dp[tmp] = i;
  }
}
