n, x, M = gets.split.map(&:to_i)

visited = [nil] * M
chain = []

seconds = 0
while visited[x].nil?
    chain << x
    visited[x] = seconds
    x = x * x % M
    seconds += 1
end

start = visited[x]
length = seconds - start

chain_sum = [0]
for e in chain
    chain_sum << chain_sum[-1] + e
end

answer = 0
if n < start
    answer += chain_sum[n]
    n = 0
else
    answer += chain_sum[start]
    n -= start
end

answer += (chain_sum[seconds] - chain_sum[start]) * (n / length)
answer += chain_sum[start + (n % length)] - chain_sum[start]
puts answer

