#include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; ll mod_exp(ll b, ll e, ll m){ if (e > 0 && b == 0) return 0; ll ans = 1; b %= m; while (e > 0){ if ((e & 1LL)) ans = (ans * b) % m; e = e >> 1LL; b = (b*b) % m; } return ans; } int main(){ ll N, M, P, Q, x, f, y; cin >> N >> M >> P >> Q; for (int i=0; i> x >> f; if (x == 0){ cout << (f == 0 ? M : 0) << endl; } else if (gcd(x, P) != 1) cout << 0 << endl; else{ y = (mod_exp(x, P-2, P) * f) % P; if (M < y) cout << 0 << endl; else cout << (M-y)/P+(f != 0) << endl; } } return 0; }