N,M,P,Q = map(int,input().split()) num = P-2 num = int(bin(num)[2:]) for i in range(Q): x,f = map(int,input().split()) cels = [] res = 1 if x%P == 0: if f == 0: print(M) else: print(0) else: for j in range(0,len(str(num))): if cels == []: cels.append(x) else: cels.append((cels[-1]**2)%P) if str(num)[j] == "1": res *= cels[-1] res %= P y = (f*res)%P if y <= M and y != 0: print((M-y)//P+1) elif y == 0: print((M-y)//P) else: print(0)