#include <bits/stdc++.h>
using namespace std;
int vis[101000];
int r[101000 * 10];
int main() {
  int a, b, m, r0, i, j, tt, ans;
  while (scanf("%d%d%d%d", &a, &b, &m, &r0) != EOF) {
    memset(vis, 0, sizeof(vis));
    vis[r0] = 1;
    tt = 2;
    r[1] = r0;
    vis[r0] = 1;
    while (1) {
      int tmp = (a * r[tt - 1] + b) % m;
      r[tt] = tmp;
      if (vis[tmp]) {
        ans = tt - vis[tmp];
        break;
      } else
        vis[tmp] = tt, tt++;
    }
    printf("%d\n", ans);
  }
  return 0;
}
