import Foundation

var input = readLine()!.split(separator: " ")
let n = Int(input[0])!
let x = Int(input[1])!
let m = Int(input[2])!
var s: [Int] = .init(repeating: 0, count: 100001)
var f = x
var first = 1
var last = 0
s[f] = 1
for i in 2...n {
    f = (f * f) % m;
    if s[f] != 0 {
        first = s[f]
        last = i
        break
    } else {
        s[f] = i
        first = i
    }
}
var t = s.enumerated().filter { $0.element != 0 }.sorted { $0.element < $1.element }.map { $0.offset }
if first == n {
    print(t.reduce(0, +))
} else {
    print(first, last)
    first -= 1 ; last -= 1
    let x = (n - first) / (last - first)
    let y = (n - first) % (last - first)
    print(t[..<first].reduce(0, +) + t[first..<last].reduce(0, +) * x + (t[first..<(first+y)].reduce(0, +)))
}