class LoopSequenceSum(untilLoop: LongArray, inLoop: LongArray, private val mod: Long) {
    private val mUntilLoop: LongArray = LongArray(untilLoop.size + 1){0L}
    private val mInLoop: LongArray = LongArray(inLoop.size + 1) {0L}
    private val untilLoopSize = untilLoop.size
    private val loopSize = inLoop.size
    init {
        for (i in untilLoop.indices) {
            mUntilLoop[i + 1] = untilLoop[i] + mUntilLoop[i]
        }
        for (i in inLoop.indices) {
            mInLoop[i + 1] = inLoop[i] + mInLoop[i]
        }
    }
    operator fun get(length: Long): Long {
        if (length <= untilLoopSize) return mUntilLoop[length.toInt()]
        return mUntilLoop.last() + getInLoop(length - untilLoopSize)
    }
    private fun getInLoop(length: Long): Long {
        val loopCount = length / loopSize
        val rest = length % loopSize
        return loopCount * mInLoop.last() + mInLoop[rest.toInt()]
    }
    companion object {
        operator fun invoke(x: Int, m: Int): LoopSequenceSum {
            val prev = IntArray(m.toInt()){-1}
            var count = 0
            var current = x.toLong()
            while (prev[current.toInt()] == -1) {
                prev[current.toInt()] = count++
                current = (current * current) % m
            }
            val untilLoop = LongArray(prev[current.toInt()]){0}
            val inLoop = LongArray(count - untilLoop.size){0}
            current = x.toLong()
            for (i in untilLoop.indices) {
                untilLoop[i] = current
                current = (current * current) % m
            }
            for (i in inLoop.indices) {
                inLoop[i] = current
                current = (current * current) % m
            }
            return LoopSequenceSum(untilLoop, inLoop, m.toLong())
        }
    }
}

fun main() {
    val (n, x, m) = readLine()!!.trim().split(' ').map(String::toLong)
    val loopSum = LoopSequenceSum(x.toInt(), m.toInt())[n]
    println(loopSum)
}