MA = 5*10**6+1 s = [0]*(MA) s[1] = 2 for i in range(2,MA): for j in range(i,MA,i): s[j] += 1 t = int(input()) for _ in range(t): a,p = map(int,input().split()) if s[p] == 1: print(pow(a,p*(p+1)//2,p)) else: print(-1)