main = mapM_ (print . solve) . analyze . map (map read . words) . lines =<< getContents
analyze [] = []
analyze ([n]:cs) = as:analyze bs where (as,bs) = splitAt n cs
solve = foldr (\[a,b] c -> ((b-((a+c)`mod`b))`mod`b)+c) 0