fun str() = readLine()!!
fun int() = str().toInt()
fun long() = str().toLong()

fun read(d: String = " ") = str().split(d)
fun <T> list(d: String = " ", f: String.() -> T) = read(d).map { f(it) }
fun list() = list { toInt() }

fun <T> MutableList<T>.removeLast() = this.removeAt(this.lastIndex)

//const val mod = 998244353L

fun main() {
    abc000X()
}

fun abc000X() {
    val (n, x, mod) = list { toLong() }


    var v = x
    var r = x

    val a = Array(mod.toInt()) { -1L to -1L }

    var i = 1L
    var f = true
    while (i < n) {
        ++i

        v = v * v % mod
        r += v

        if (f) {
            val (b, c) = a[v.toInt()]
            if (b < 0L) {
                a[v.toInt()] = i to r
            } else {
                f = false
                val l = (n - i) / (i - b)
                val m = r - c
                System.err.println(l to m)
                r += l * m
                i += l * (i - b)
            }
        }
    }
    println(r)
}
