object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datN,datX,datM) = readLine.split(" ").map(_.toLong)

    val a2 = (datX * datX) % datM

    def makeAn(res : Long, an : Long, count : Long) : Long = {
      if (count == 0) res
      else {
        val ann = (an * an) % datM
        val sum = res + ann
        makeAn(sum, ann, count - 1)
      }
    }

    val ans = if ((datN - 2) > datM) {
      val loop = makeAn(0, a2, datM)
      datX + a2 + ((datN - 2) / datM) * loop + makeAn(0, a2, (datN - 2) % datM)
    } else {
      datX + a2 + makeAn(0, a2, datN - 2)
    }
    println(ans)
  }
}
