#include #include #include #include #include #include #include #include #include #include using ll = long long; using namespace std; int main() { ll n, m, p, q; cin >> n >> m >> p >> q; for (int i = 0; i < q; i++){ ll x, f, x1 = 1, p1, y; cin >> x >> f; if (!(x%p) && f == 0){ cout << m << endl; continue; } else if (!(x%p)){ cout << 0 << endl; continue; } p1 = p - 2; while (p1){ if (p1 & 1){ x1 *= x; x1 %= p; } x *= x; x %= p; p1 >>= 1; } x1 %= p; y = x1 * f % p; if (!y) cout << m/p << "\n"; else cout << (m - y + p)/p << "\n"; } }