import math n, m, p, q = map(int, input().split()) for _ in range(q): x, f = map(int, input().split()) if f == 0: if math.gcd(p, x) == 1: print(m // p) else: print(m) elif math.gcd(p, x) != 1: print(m) else: x %= p y = f * pow(x, p - 2, p) % p print(m // p + (m % p >= y))