import scala.annotation.tailrec

object Main extends App {
  override def main(args: Array[String]): Unit = {

    val in: java.util.Scanner = new java.util.Scanner(System.in)
    Iterator
      .continually((in.nextInt, in.nextInt, in.nextInt, in.nextInt, in.nextInt))
      .takeWhile(_ != (0, 0, 0, 0, 0))
      .map(n => {
        val seq = for (x <- 1 to n._1) yield in.nextInt
        (n, seq)
      }).map(x => solve(x._1._1, x._1._2, x._1._3, x._1._4, x._1._5, x._2)).foreach(println)
  }

  def solve(n: Int, a: Int, b: Int, c: Int, x: Int, input: Seq[Int]): Int = {

    def next(seed: Int): Int = (a * seed + b) % c

    val MAX = 10000

    @tailrec
    def rec(xx: Int, seq: Seq[Int], c: Int): Int = (xx, seq, c) match {
      case (_, Nil, _) => c
      case (x, s +: xs, j) if (x == s) => rec(next(x), xs, j + 1)
      case (_, _, MAX) => 0
      case (x, s, j) => rec(next(x), s, j + 1)
    }

    return rec(x, input, 0) - 1

  }
}