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

var sum = 0
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)
        var loopSum: Int {
            var localSum = 0
            for j in firstOfLoop..<i-1 {
                localSum += nowHistory[j]
            }
            return localSum
        }
        let quotient = ( n - i ) / loopCount
        sum += quotient * loopSum
        i += quotient * loopCount
        nowHistory = []
    } else {
        nowHistory.append(now)
    }
    sum += now
    i += 1
    now = (now * now) % m
}

print(sum)

