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