import Control.Applicative ((<$>), (<*>), (<*), (*>), (<$))
import Control.Monad
import Data.List

main :: IO ()
main = do
  n <- getl read
  solve n <$> replicateM n (getl $ map read . words) >>= print

solve :: Int -> [[Int]] -> Int
solve n xs = f 0 as bs
  where
    [as, bs] = map reverse $ transpose xs
    f c [] [] = c
    f c (y:ys) (z:zs) = f (c+d) ys zs
      where
        d = if (y+c) `mod` z == 0 then 0 else z - (y+c) `mod` z
        
getl :: (String -> a) -> IO a
getl f = f <$> getLine
