T=int(input()) for t in range(T): M=int(input()) D=list(map(int,input().split())) S="" for x in range(9): S+=str(x+1)*D[x] if S: S=int(S) else: S=0 S*=10**9 S+=(-S)%M print(S)