from bisect import bisect_left M = int(input()) n = 28 G = list(map(int, input().split())) H = list(map(int, input().split())) l = 18 L = [[] for _ in range(l + 1)] for bit in range(1 << l): pc = 0 tot = 0 for i in range(l): if bit >> i & 1: pc += 1 tot += G[i] else: tot += H[i] L[pc].append(tot % M) for i in range(l + 1): L[i].sort() R = [] for bit in range(1 << (n - l)): pc = 0 tot = 0 for i in range(n - l): if bit >> i & 1: pc += 1 tot += G[i + l] else: tot += H[i + l] R.append((pc, tot % M)) Q = int(input()) for _ in range(Q): k, x = map(int, input().split()) ans = 0 for kk, vv in R: t = k - kk if t < 0 or l < t: continue low = (x - vv) % M upp = M - vv if low <= upp: ans += bisect_left(L[t], upp) - bisect_left(L[t], low) else: ans += bisect_left(L[t], upp) + len(L[t]) - bisect_left(L[t], low) print(ans)