#pragma GCC target("avx2") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #include using namespace std; using ll = long long int; using ull = unsigned long long int; using ld = long double; ll modinv(ll A,ll M){ //A*r+B*n=gcd(A,B) A %= M; if(A == 0 || __gcd(A,M) != 1){ //cout << "Error modinv(" << A << "," << M << ")" << endl; return -1; } ll B = M,U = 1,V = 0; while(B){ ll T = A / B; A -= T * B; swap(A,B); U -= T * V; swap(U,V); } U %= M; if(U < 0) U += M; return U; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); ll N,M,P,Q; cin >> N >> M >> P >> Q; for(ll q = 0;q < Q;q++){ ll x,f; cin >> x >> f; x %= P; if(x == 0){ if(f == 0) cout << M << endl; else cout << 0 << endl; } else{ ll y = (f * modinv(x,P)) % P; ll ans = M / P; if(y != 0 && y <= M % P) ans++; cout << ans << endl; } } }