import Data.List

main = interact $ unlines . map (show' . luck_manipulator) . read' . lines
 where
  read' ("0 0 0 0 0":_) = []
  read' (nabcx:rs:xs) = ((n,a,b,c,x), map read (words rs)) : read' xs
   where [n,a,b,c,x] = map read (words nabcx)
  show' r = case r of {Nothing -> "-1"; (Just x) -> show x}

luck_manipulator ((n,a,b,c,x),rs) =
 case (foldr1 push $ map (\r -> findIndices (== r) rand) rs) of {[] -> Nothing; (x:xs) -> Just x}
  where
   push [] _ = []
   push _ [] = []
   push xs1 xs2 = dropWhile (<= minimum xs1) xs2
   rand = take 10001 (iterate (\x -> (a*x + b) `mod` c) x) 