import sys #sys.setrecursionlimit(10 ** 6) INF = float('inf') #10**20,2**63に変えるのもあり MOD = 10**9 + 7 MOD2 = 998244353 from collections import defaultdict def ceil(A,B): return -(-A//B) def egcd(a, b): if a == 0: return b, 0, 1 else: g, y, x = egcd(b % a, a) return g, x - (b // a) * y, y def crt(b1, m1, b2, m2): # 中国剰余定理 # x ≡ b1 (mod m1) ∧ x ≡ b2 (mod m2) <=> x ≡ r (mod m) # となる(r. m)を返す # 解無しのとき(0, -1) d, p, q = egcd(m1, m2) if (b2 - b1) % d != 0: return 0, -1 m = m1 * (m2 // d) # m = lcm(m1, m2) tmp = (b2 - b1) // d * p % (m2 // d) r = (b1 + m1 * tmp) % m return r, m def solve(): def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def LC(): return list(input()) def IC(): return [int(c) for c in input()] def MI(): return map(int, sys.stdin.readline().split()) N,M,P,Q = MI() import math for q in range(Q): X,F = MI() X%=P G = math.gcd(X,P) #print(G) if (F % G != 0): print(0) continue period = P//G #周期 ans = M//period rest_m = M%period r,m=crt(F,P,0,X) #print("R:",r,"M:",m) if(r==0): r+=m #print(r//X,rest_m) if(r//X<=rest_m): print(ans+1) else: print(ans) return solve()