def calculate_parentship(N, M, P, Q, queries): result = [] for i in range(Q): x, f = queries[i] y_count = 0 for y in range(1, M + 1): if (x * y) % P == f: y_count += 1 result.append(y_count) return result # 入力を受け取る N, M, P, Q = map(int, input().split()) queries = [] for _ in range(Q): x, f = map(int, input().split()) queries.append((x, f)) # 答えを計算して出力 results = calculate_parentship(N, M, P, Q, queries) for res in results: print(res)