import sys input = sys.stdin.readline from collections import Counter from bisect import bisect 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].sort() 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]: ANS+=LIST1[i][c]*(bisect(LIST2[K-i],M-c-1)-bisect(LIST2[K-i],X-c-1)) ANS+=LIST1[i][c]*(bisect(LIST2[K-i],2*M-c-1)-bisect(LIST2[K-i],M+X-c-1)) print(ANS)