import sys input = sys.stdin.readline from collections import Counter from bisect import bisect_left M=int(input()) G=list(map(int,input().split())) H=list(map(int,input().split())) DP1=[(0,0)] for i in range(14): NDP1=[] for x,y in DP1: NDP1.append((x+1,(y+G[i])%M)) NDP1.append((x,(y+H[i])%M)) DP1=NDP1 DP2=[(0,0)] for i in range(14,28): NDP2=[] for x,y in DP2: NDP2.append((x+1,(y+G[i])%M)) NDP2.append((x,(y+H[i])%M)) DP2=NDP2 LIST1=[[] for i in range(29)] for x,y in DP1: LIST1[x].append(y) for i in range(29): LIST1[i]=Counter(LIST1[i]) LIST2=[[] for i in range(29)] for x,y in DP2: LIST2[x].append(y) for i in range(29): LIST2[i]=Counter(LIST2[i]) Q=int(input()) for tests in range(Q): K,X=map(int,input().split()) ANS=0 for i in range(K+1): for c in LIST1[i]: for c2 in LIST2[K-i]: if (c+c2)%M>=X: ANS+=LIST1[i][c]*LIST2[K-i][c2] print(ANS)