fun main(args: Array<String>) {
    val sp = readLine()!!.split(" ")

    val n = sp[0].toLong()
    val x = sp[1].toInt()
    val m = sp[2].toInt()


    val first = Array(m) { -1 }
    val sums = Array(m + 1) { 0L }

    var step = 0
    first[x] = step

    var a = x.toLong()
    val period: Int
    val start: Int
    while (true) {
        step++
        sums[step] = (sums[step - 1] + a)
        a = (a * a) % m
        val prev = first[a.toInt()]
        if (prev == -1) first[a.toInt()] = step
        else {
            period = step - prev
            start = prev
            break
        }
    }

    if (n < start) println(sums[n.toInt()])
    else {
        var res = sums[start]
        res += (sums[start + period] - sums[start]) * ((n - start) / period)
        val rest = ((n - start) % period).toInt()
        res +=  sums[start + rest] - sums[start]

        println(res)
    }
}