#include <bits/stdc++.h>
using namespace std;
long long a, b, p, x, cnt;
pair<long long, long long> exgcd(long long A, long long B) {
  if (B == 0) return pair<long long, long long>(1, 0);
  pair<long long, long long> Pxy = exgcd(B, A % B);
  return pair<long long, long long>(Pxy.second,
                                    Pxy.first - (A / B) * Pxy.second);
}
int main() {
  cin >> a >> b >> p >> x;
  long long Pow = a;
  for (long long i = 1; i < p && i <= x; i++) {
    long long F = ((exgcd(Pow, p).first) % p) * b;
    F %= p;
    if (F < 0) F += p;
    if (F > i) F -= p;
    F = i + (i - F) * (p - 1);
    if (F <= x) cnt += ((x - F) / (p * (p - 1)) + 1);
    Pow = (Pow * a) % p;
  }
  cout << cnt << '\n';
}
