def extended_gcd(a, b): if b == 0: return a, 1, 0 else: d, x, y = extended_gcd(b, a % b) return d, y, x - (a // b) * y def count_valid_y(n, m, x, p, f): d, _, _ = extended_gcd(x, p) if f % d != 0: return 0 else: p_div_d = p // d f_div_d = f // d y0 = (f_div_d * extended_gcd(x // d, p_div_d)[1]) % p_div_d count = 0 for k in range((m - y0) // p_div_d + 1): y = y0 + k * p_div_d if 1 <= y <= m: count += 1 return count N, M, P, Q = map(int, input().split()) queries = [list(map(int, input().split())) for _ in range(Q)] for x, f in queries: result = count_valid_y(N, M, x, P, f) print(result)