let nxm = readLine()!.split(separator: " ").map {Int($0)!}
let n = nxm[0], x = nxm[1], m = nxm[2]

var sum = 0
var cumSum = [Int]()
var now = x
var nowHistory = [Int]()

var i = 1
while i <= n {
    if nowHistory.contains(now) {
        let firstOfLoop = nowHistory.firstIndex(of: now)!
        let loopCount = i - (firstOfLoop+1)
        let loopSum = cumSum[i-2] - cumSum[firstOfLoop-1]
        sum += (( n - i ) / loopCount) * loopSum
        i = n - (( n - i + 1 ) % loopCount) + 1
        nowHistory = []
    } else {
        nowHistory.append(now)
    }
    sum += now
    cumSum.append(sum)
    i += 1
    now = (now * now) % m
}

print(sum)
