n = int(input())
for _ in range(n):
a,b = map(int, input().split())
t = ((a%10)**(b%4+4))%10
print(10 if t==0 else t)
D = {4:[4,6], 9:[9,1],
2:[2,4,8,6], 3:[3,9,7,1],
7:[7,9,3,1], 8:[8,4,2,6]}
n = int(input())
for _ in range(n):
a,b = map(int, input().split())
a = a%10
if a in [0,1,5,6]:
print(10 if a==0 else a)
elif a in [4,9]:
print(D[a][0] if b%2==1 else D[a][1])
else:
print(D[a][3] if b%4==0 else D[a][b%4-1])