import std; void main () { int N, M, P, Q; readln.read(N, M, P, Q); auto x = new int[](Q); auto f = new int[](Q); foreach (i; 0 .. Q) { readln.read(x[i], f[i]); } // x[i] * y mod P = f[i]なるyの数え上げ // y = f[i] / x[i] mod Pなるyの数え上げ // x[i]とPが互いに素であるとき、またそのときのみx[i]^-1が定義される。 // P素数より、 // 1. x[i] % P != 0: y = f[i] / x[i] mod Pとなるyで成立 // 2. そうでないとき: // 1. f[i] = 0ならすべてのyで成立、 // 2. f[i] != 0ならすべてのyで不成立 // P素数なのでフェルマーの小定理を使ってよい。 auto ans = new int[](Q); foreach (i; 0 .. Q) { if (x[i] % P == 0) { if (f[i] == 0) { ans[i] = M; } else { ans[i] = 0; } } else { long v = f[i] * mod_inv(x[i], P) % P; if (M < v) { ans[i] = 0; } else { ans[i] = M / P; int rem = M % P; if (v <= rem) { ans[i]++; } if (v == 0) { ans[i]--; } } } } writefln("%(%s\n%)", ans); } void read (T...) (string S, ref T args) { import std.conv : to; import std.array : split; auto buf = S.split; foreach (i, ref arg; args) { arg = buf[i].to!(typeof(arg)); } } long mod_pow (long a, long x, const long MOD) in { assert(0 <= x, "x must satisfy 0 <= x"); assert(1 <= MOD, "MOD must satisfy 1 <= MOD"); assert(MOD <= int.max, "MOD must satisfy MOD*MOD <= long.max"); } do { // normalize a %= MOD; a += MOD; a %= MOD; long res = 1L; long base = a; while (0 < x) { if (0 < (x&1)) (res *= base) %= MOD; (base *= base) %= MOD; x >>= 1; } return res % MOD; } // check mod_pow static assert(__traits(compiles, mod_pow(2, 10, 998244353))); long mod_inv (const long x, const long MOD) in { import std.format : format; assert(1 <= MOD, format("MOD must satisfy 1 <= MOD. Now MOD = %s.", MOD)); assert(MOD <= int.max, format("MOD must satisfy MOD*MOD <= long.max. Now MOD = %s.", MOD)); } do { return mod_pow(x, MOD-2, MOD); }