import Control.Monad
import Control.Applicative

main :: IO ()
main = do
  n <- readLn :: IO Int
  ns <- replicateM n readLn :: IO [Int]
  print $ solve ns

solve :: [Int] -> Int
solve [n, m] = m - n
solve (n:ns:nss) = go ns (ns - n) nss
  where
    go x y [] = y
    go x y (z:zs)
      | z < x = go z y zs
      | y < z - x = go x (z-x) zs
      | otherwise = go x y zs