import Control.Applicative
import Control.Monad

judge :: [Int] -> Int
judge xs =
  let k = head xs
      p = last xs
  in
      if k > p then
        if k `mod` p == 0 then
          p
        else
          k `mod` p
      else
        k

solver :: [[Int]] -> [Int]
solver = map judge

main :: IO()
main = do
  n <- (read :: String -> Int) <$> getLine
  inputs <- map (map (read :: String -> Int) . words) <$> replicateM n getLine
  mapM_ print $ solver inputs