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: ans=int(S) ans*=10**9 ans+=(-ans)%M else: ans=M print(ans)