#include <bits/stdc++.h>
using namespace std;
int life[1000015];
long long pows(long long x, long long y, long long p) {
  long long ans = 1;
  while (y) {
    if (y % 2) ans = (x * ans) % p;
    x = (x * x) % p;
    y >>= 1;
  }
  return ans;
}
long long ask(long long a, long long x, long long b, long long y, long long n) {
  if (b == y) b = 0;
  long long ans;
  if (y >= 2)
    ans = (a * y * pows(y, x - 2, x) + b * x * pows(x, y - 2, y)) % (x * y);
  else {
    for (int i = 1; i <= y; i++) {
      if ((x * i + a) % y == b) {
        ans = x * i + a;
        break;
      }
    }
  }
  return (n / (x * y)) + (n % (x * y) >= ans);
}
int main() {
  long long ans = 0, gg;
  long long a, b, p, x, now, t;
  scanf("%lld%lld%lld%lld", &a, &b, &p, &x);
  if (p > 2) {
    life[a] = 1;
    now = a;
    t = 1;
    for (int i = 2; !life[(a * now) % p]; i++) {
      now = (now * a) % p;
      life[now] = i;
      t = i;
    }
    for (int i = 1; i < p && i <= x; i++) {
      gg = (b * pows(i * 1LL, p - 2, p)) % p;
      if (life[gg]) ans += ask(i * 1LL, p, life[gg], t, x);
    }
  } else
    ans = (x + 1) / 2;
  printf("%lld\n", ans);
  return 0;
}
