import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min

val br = BufferedReader(InputStreamReader(System.`in`))
val out = PrintWriter(System.out)

fun main() {
    br.use { out.use {
        solve()
        out.flush()
    } }
}

fun solve() {
//    var pre = 2
//    var aaaaaa = 0
////    out.println("1:" +pre)
//    out.println(pre)
//    for (i in 1..12) {
//        aaaaaa += pre
//        val tmp = pre * pre % 1001
//
//
//        out.println("${i}:" + aaaaaa)
//        out.println(tmp)
//        pre = tmp
//    }
////    out.println(aaaaaa)
//    out.println()

    val (n, x, m) = readLongList()

//    val set = mutableSetOf<Long>()
    val indexMap = mutableMapOf<Long, Int>()
    var cur = x
    var curIndex = 0
    while (indexMap.containsKey(cur) == false) {
        indexMap[cur] = curIndex
        curIndex++
        cur = (cur % m) * (cur % m) % m
    }

    val loopFrom = indexMap[cur]!!

    if (n <= loopFrom) {
        var ans = 0L
        var pre = x
        repeat(n.toInt()) {
            ans += pre
            pre = (pre % m) * (pre % m) % m
        }
        out.println(ans)
        return
    } else {
        val firstSum = indexMap.filter { it.value < loopFrom }.keys.sum()
        val loopSum = indexMap.filter { it.value >= loopFrom }.keys.sum()
        val loopCount = indexMap.count() - loopFrom

        var ans = firstSum

        val remain = max(0, n - loopFrom)
        val aaa = remain / loopCount
        val modRemain = remain % loopCount

        ans += aaa * loopSum

        var pre = cur
        repeat(modRemain.toInt()) {
            ans += pre
            pre = (pre%m) * (pre%m) % m
        }
        out.println(ans)
        return
    }
}

fun readInteger() = Integer.parseInt(br.readLine())
fun readLong() = java.lang.Long.parseLong(br.readLine())
fun readStringList() = br.readLine()!!.split(' ')
fun readIntegerList() = readStringList().map(Integer::parseInt)
fun readLongList() = readStringList().map(java.lang.Long::parseLong)
fun readDoubleList() = readStringList().map(java.lang.Double::parseDouble)
