using System; namespace No02324_TwoCountriesWithinUEC { internal class Program { static void Main(string[] args) { string[] param = Console.ReadLine().Split(' '); int n = int.Parse(param[0]); int m = int.Parse(param[1]); int p = int.Parse(param[2]); int q = int.Parse(param[3]); int[] result = new int[q]; for (int i = 0; i < q; i++) { string[] param2 = Console.ReadLine().Split(' '); int x = int.Parse(param2[0]); int f = int.Parse(param2[1]); int xMod = x % p; if (xMod == 0) { if (f == 0) { result[i] = m; } else { result[i] = 0; } } else { long y = f * RepPow(x, p - 2, p) % p; if (y != 0 && y <= m) { result[i] = m / p + 1; } else { result[i] = m / p; } } } for (int i = 0; i < q; i++) { Console.WriteLine(result[i]); } } //x^p % mod static long RepPow(long n, long p, int mod) { if (p == 0) { return 1; } if (p % 2 == 0) { var x = RepPow(n, p / 2, mod); return (x * x) % mod; } else { return RepPow(n, p - 1, mod) * n % mod; } } } }