import java.util.*

fun main() {
    val pw = java.io.PrintWriter(System.out)
    Problem.solve(Scanner(System.`in`), pw)
    pw.flush()
}

object Problem {
    val MOD = 998244353L
    fun solve(sc: Scanner, pw: java.io.PrintWriter) {
        val N = sc.next().toLong()
        val X = sc.next().toLong()
        val M = sc.next().toInt()
        val S = LongArray(M * 100)
        val Q = LongArray(M) { -1L }
        var sum = 0L
        var a = X
        var i = 0L
        while (i < N) {
            if (a == 0L) break
            if (Q[a.toInt()] >= 0) {
                val d = (i - Q[a.toInt()]).toInt()
                val l = S[i.toInt()] - S[i.toInt() - d]
                val r = (N - i) / d
                if (r > 0) {
                    sum += l * r
                    i += d * r
                }
                while (i < N) {
                    sum += a
                    a = (a * a) % M
                    i++
                }
                break
            }
            Q[a.toInt()] = i

            sum += a
            S[i.toInt() + 1] = sum
            a = (a * a) % M
            i++
        }
        pw.println(sum)
    }
}
