n, x, m = gets.split.map(&:to_i)
ary = [x]
v = Array.new(m)
v[x] = 0

a = x * x % m
i = 0
while !v[a]
    v[a] = (i += 1)
    ary << a
    a = a * a % m
end

if i + 1 >= n
    ans = ary[0, n].sum
else
    j = v[a]
    ans = ary[0, j].sum
    n -= j

    s, t = n.divmod(i - j + 1)
    ans += ary[j .. i].sum * s
    ans += ary[j, t].sum
end

p ans