n,m,p,q=map(int,input().split()) for _ in range(q): x,f=map(int,input().split()) if f==0: if x%p==0: print(m) else: print(m//p) else: inv=f*pow(x,p-2,p)%p print((m-inv+p)//p)