import Data.Maybe
import qualified Data.ByteString.Char8 as B
main = mapM_ (print . solve) . analyze . map (map readInt . B.words) . B.lines =<< B.getContents
readInt = fst . fromJust . B.readInt
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