import Control.Monad

main :: IO ()
main = do
  n <- readLn
  ls <- replicateM n getLine
  mapM_ print $ solve (map (map read . words) ls)

solve :: [[Int]] -> [Int]
solve = map fix
  where
    fix :: [Int] -> Int
    fix [k,p]
      | amari == 0 = p
      | otherwise = amari
      where amari = k `mod` p