import qualified Control.Monad as M main :: IO () main = do t <- readLn _ <- solve t return () solve :: Int -> IO [()] solve t = M.replicateM t solve' solve' :: IO () solve' = do [a, p] <- map read . words <$> getLine print $ solve'' a p solve'' :: Int -> Int -> Int solve'' a p = if isPrime p then (a ^ (fact p)) `mod` p else -1 -- ref: https://gist.github.com/marcoscastro/a4c109bb6df608f14bf5 isPrime :: Int -> Bool isPrime 1 = False isPrime 2 = True isPrime n | (length [x | x <- [2 .. n - 1], n `mod` x == 0]) > 0 = False | otherwise = True fact :: Int -> Int fact 0 = 1 fact n = n * fact (n - 1)